Predict the output of following C programs.
The output of above programs and all such programs can be easily guessed by remembering following simple rules about postfix ++, prefix ++ and * (dereference) operators
1) Precedence of prefix ++ and * is same. Associativity of both is right to left.
2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.
(Refer: Precedence Table)
The expression ++*p has two operators of same precedence, so compiler looks for assoiativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr = 11, arr = 20, *p = 11“.
The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr = 10, arr = 20, *p = 20“.
The expression *++p has two operators of same precedence, so compiler looks for assoiativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of third program is “arr = 10, arr = 20, *p = 20“.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference and Similarities between PHP and C
- Difference between Stop and Wait protocol and Sliding Window protocol
- Similarities and Difference between Java and C++
- Difference between Yaacomo and and XAP
- Difference between VoIP and and POTS
- Difference Between malloc() and calloc() with Examples
- What is the difference between single quoted and double quoted declaration of char array?
- Difference between "int main()" and "int main(void)" in C/C++?
- Difference Between DOS and Windows
- Difference between User Level thread and Kernel Level thread
- What’s difference between The Internet and The Web ?
- Difference between Priority Inversion and Priority Inheritance
- What’s difference between Linux and Android ?
- What’s difference between header files "stdio.h" and "stdlib.h" ?
- Difference between HTML and HTTP
- Difference between http:// and https://
- What's difference between MMU and MPU?
- What's difference between Microcontroller (µC) and Microprocessor (µP)?
- What's the difference between Scripting and Programming Languages?
- What is the difference between "char a" and "char a"?
Improved By : srinam