JJJJJJ
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Operator Precedence Must Read: [Operator Precedence and Associativity in C](https://www.geeksforgeeks.org/operator-precedence-and-associativity-in-c/) ## 1 What is the output of the following program? ```c #include <stdio.h> int main() { int i; i = 1, 2, 3; printf("i = %d\n", i); getchar(); return 0; } ``` :::spoiler Answer Output: `i = 1` The above program prints 1. Associativity of comma operator is from left to right, but = operator has higher precedence than comma operator.  Therefore the statement i = 1, 2, 3 is treated as (i = 1), 2, 3 by the compiler. ::: ## 2 What is the output of the following program? ```c #include <stdio.h> int main() { int i; i = (1, 2, 3); printf("i = %d\n", i); getchar(); return 0; } ``` :::spoiler Answer Output: `i = 3` The above program prints 3. See [Operator Precedence and Associativity in C](https://www.geeksforgeeks.org/operator-precedence-and-associativity-in-c/). ::: ## 3 What is the output of the following program? ```c int main() { char str[]= "geeks\nforgeeks"; char *ptr1, *ptr2; ptr1 = &str[3]; ptr2 = str + 5; printf("%c", ++*str - --*ptr1 + *ptr2 + 2); printf("%s", str); getchar(); return 0; } ``` :::spoiler Answer Output: heejs forgeeks Explanation: Dereference Operator 的優先級和 Prefix increment, decrement 以及 `+, -` 一樣 ,Associativity 都是 Right-to-Left。 因此 `++*str - --*ptr1 + *ptr2 + 2` 等同於 `++(*str) - (--(*ptr1)) + (*ptr2) + 2`。 這裡沒有 postfix operator,不能將 `++*str - --*ptr1` 看成 `++*str-- -*ptr1`,因為 `-` 要連續兩個寫在一起才會看作是 postfix (or prefix) decrement。 Initially ptr1 points to ‘k’ and ptr2 points to ‘\n’ in “geeks\nforgeeks”. In print statement value at str is incremented by 1 and value at ptr1 is decremented by 1. So string becomes “heejs\nforgeeks” . First print statement becomes `printf(“%c”, ‘h’ – ‘j’ + ‘\n’ + 2)` which is: `‘h’ – ‘j’ + ‘\n’ + 2 = -2 + ‘\n’ + 2 = ‘\n’` First print statements newline character. and next print statement prints “heejs\nforgeeks”. See [Operator Precedence and Associativity in C](https://www.geeksforgeeks.org/operator-precedence-and-associativity-in-c/). ::: ## 4 What is the output of the following program? ```c #include <stdio.h> int main() { int x, y = 2, z, a; printf("%d\n", a); if (x = y % 2) z = 2; a = 2; printf("%d %d ", z, x); return 0; } ``` :::spoiler Answer Output:  0 0 Explanation:  `z, a` 皆為 0 (implicit initialization),再加上 The precedence of modulus is higher than assignment。 ::: ## 5 What is the output of the following program? ```c int main() { char arr[] = "geeksforgeeks"; char *ptr = arr; while(*ptr != '\0') ++*ptr++; printf("%s %s", arr, ptr); getchar(); return 0; } ``` :::spoiler Answer Output: hffltgpshfflt Explanation: The crust of this question lies in expression `++*ptr++`. operator precedence and associativity: Postfix ++ (left-to-right) 優先於 Prefix ++ (right-to-left) Dereference * (right-to-left) 所以 `++*ptr++` 等同於 `++(*(ptr++))`。 postfix 因為 precedence 較高所以會先被 evaluate,至於 prefix 和 dereference 則是因為 associativity 是由右到左,因此會先 evaluate dereference operator。 - [Difference between ++*p, *p++ and *++p](https://www.geeksforgeeks.org/difference-between-p-p-and-p/) - [Operator Precedence and Associativity in C](https://www.geeksforgeeks.org/operator-precedence-and-associativity-in-c/). ::: ## 6 What is the output of the following program? ```clike int main() { int a = 5, b = 7, c; c = a+++b; printf("%d, %d, %d\n", a, b, c); return 0; } ``` :::spoiler Answer Output: 6, 7, 12 Explaination: 因為 Postfix operator precendence 比 `+` 還要高,因此 `c = a+++b;` 等同於 `c = (a++) + b`。 ::: ## 7 What is the output of the following program? ```clike #include<stdio.h> int main(void) { char *ptr = "Linux"; printf("%c\n",*ptr++); printf("%c\n",*ptr); return 0; } ``` :::spoiler Answer Output: L i Explaination: 因為 Postfix operator precendence 比 `*` 還要高,因此 `*ptr++` 等同於 `*(ptr++)`。 而 `(ptr++)` 回傳的會是原先的 `ptr` 位置給 `*` 去 dereference,在這之後 `ptr` 的值才被 `++` 給下一行的 `printf`。 ::: ## 8 Predict the output of below program. ```clike int main() { int x, y = 5, z = 5; x = y==z; printf("%d", x); getchar(); return 0; } ``` :::spoiler Answer Output: 1 Explaination: 因為 == precendence 比 `=` 還要高,因此 `x = y==z` 等同於 ` x = (y==z)`。 ::: ## 9 What is the output of the following program? ```clike #include<stdio.h> #define L 10 void main() { auto a = 10; switch (a, a*2) { case L: printf("ABC"); break; case L*2: printf("XYZ"); break; case L*3: printf("PQR"); break; default: printf("MNO"); case L*4: printf("www"); break; } } ``` :::spoiler Answer Output: XYZ Explaination: 因為 `,` 的 operator precedence 是所有 operators 裡面最低的,且 `,` 是一個 sequence point,所以 `(a, b)` 的 return 的結果會是 `b`,因為按照sequence 順序由左到右去 evaluate `a` 和 `b`,兩者都會被 evaluate 但是最後只會 return `b`。 ```clike int a = b, c // b is asigned to a int a = (b, c) // c is asigned to a ``` - [How does the comma operator work, and what precedence does it have?](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work-and-what-precedence-does-it-have) 所以在上面的例子中:`(a, a*2)` 會等同於 `a*2`。 ::: ## 10 What is the output of the following program? ```clike! #include <stdio.h> int main(void) { int i = 40 >> 5 << 3 >> 2 << 1; printf("%d", i); return 0; } ``` :::spoiler Answer Output: 4 Explaination: `<<, >>` operator precendence 相同,associativity 是 left-to-right,因此就由左到右開始做 bit shift 就會得到 `4`,要注意不能先把後面的總結起來,例如 `>> 5 << 3 >> 2 << 1` 看作是 `>> 3`,因為在過程中可能會有 1 bit 被 right shift 掉,left shift 回來時會變做 0。 ::: ## 11 What is the output of the following program? ```clike! #include <stdio.h> int main(void) { int i = 10 > 9 > 7 < 8; printf("%d", i); return 0; } ``` :::spoiler Answer Output: 1 Explaination: `<, >` operator precendence 相同,associativity 是 left-to-right,因此就由左到右開始做比較就會得到 1(`10 > 9` 會回傳 `1`, and so on.)。 ::: ## 12 What is the output of the following program? ```clike! #include <stdio.h> int main(void) { int x = 4, y = 4, z = 4; if (x == y == z) { printf("Hello"); } else { printf("GEEKS"); } return 0; } ``` :::spoiler Answer Output: GEEKS Explaination: `==` associativity 是 left-to-right,因此 `x == y == z` 等同於 `(x == y) == z`。 ::: ## 13 What is the output of the following program? ```clike! #include <stdio.h> int main(void) { int x = 10, y = 15; x ^= y ^= x ^= y; printf("%d %d", x, y); return 0; } ``` :::spoiler Answer Output: 15 10 Explaination: `^=` associativity 是 right-to-left,因此 `x ^= y ^= x ^= y` 等同於 `(x ^= (y ^= (x ^= y)))`。 ::: ## 14 What is the output of the following program? ```clike #include <stdio.h> int main() { int x; x = 5 > 8 ? 10 : 1 != 2 < 5 ? 20 : 30; printf("Value of x:%d", x); return 0; } ``` :::spoiler Answer Output: Value of x:30 Explaination: Operator precedence: `?:` < `!=` < `<, >` 。 ::: ## 15 What is the output of the following program? ```clike #include <stdio.h> int main() { int x; x = 2 > 5 != 1 ? 5 < 8 && 8 > 2 ? !5 ? 10 : 20 : 30 : 40; printf("Value of x:%d", x); return 0; } ``` :::spoiler Answer Output: Value of x:20 Explaination: Operator precedence: `?:` < `&&` < `!=` < `<, >` < `!`。 先將所有 `?` 前的 expression 是 true or false 解出來: ```clike x = 2 > 5 != 1 ? 5 < 8 && 8 > 2 ? !5 ? 10 : 20 : 30 : 40; ``` 等價於 ```clike x = true ? true ? false ? 10 : 20 : 30 : 40; ``` 因為 `?:` 的 operator associativity is from right to left 因此 上式等價於 ```clike x = true ? true ? false ? 10 : 20 : 30 : 40; x = true ? true ? 20 : 30 : 40; x = 20; ``` 因此 `x = 20`。 ::: ## 16 What is the output of the following program? ```clike #include <stdio.h> int main() { int x; x = 2 > 5 ? 1 != 2 > 5 ? 10 : 20 : 5 < 8 ? 2 != 2 > 5 ? !5 ? 30 : !1 != 1 ? 40 : 50 : 60 : 70; printf("Value of x:%d", x); return 0; } ``` :::spoiler Answer Output: Value of x:40 Explaination: 先將所有 `?` 前的 expression 是 true or false 解出來: ```clike x = 2 > 5 ? 1 != 2 > 5 ? 10 : 20 : 5 < 8 ? 2 != 2 > 5 ? !5 ? 30 : !1 != 1 ? 40 : 50 : 60 : 70; ``` 等價於 ```clike x = false ? true ? 10 : 20 : true ? true ? false ? 30 : true ? 40 : 50 : 60 : 70; ``` 因為 `?:` 的 operator associativity is from right to left,因此當我們由左向右遇到連續的 ternary operator (`?`) 時,要先處理更右邊的 `?`。 因此 ```clike x = false ? (true ? 10 : 20) : true ? true ? false ? 30 : true ? 40 : 50 : 60 : 70; x = false ? 10 : (true ? true ? false ? 30 : true ? 40 : 50 : 60 : 70); x = true ? true ? (false ? 30 : true ? 40 : 50 : 60 : 70); x = true ? true ? true ? 40 : 50 : 60 : 70; x = true ? true ? (true ? 40 : 50 : 60 : 70); x = 40; ``` ::: ## 17 What is the output of the following program? ```clike #include <iostream> using namespace std; int main() { int x = 0, k; while (+(+x--) != 0) { x++; } printf("%d ", x); return 0; } ``` :::spoiler Answer Output: -1 Explaination: Unary + is the only dummy operator in C/C++. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator). ::: ## 18 ```clike #include <iostream> using namespace std; int main() { int i; for (i = 0; i < 0, 5; i++) printf("%d ", i); return 0; } ``` :::spoiler Answer Output: infinite loop Explaination: ```clike for (i = 0; i < 0, 5; i++) ``` 等價於 ```clike for (i = 0; (i < 0, 5) != 0; i++) ``` 因為 `()` 的 precedence 比 `,` 要高,因此會等價於 ```clike for (i = 0; (5) != 0; i++) ``` :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully