Comma operator should be used carefully
In C and C++, comma is the last operator in precedence table. So comma should be carefully used on right side of an assignment expression. For example, one might expect the output as b = 10 in below program. But program prints b = 20 as assignment has higher precedence over comma and the statement “b = 20, a” becomes equivalent to “(b = 20), a”.
#include<stdio.h> int main() { int a = 10, b; b = 20, a; // b = 20 printf(" b = %d ", b); getchar(); return 0; } |
chevron_right
filter_none
Putting a bracket with comma makes b = a (or 10).
#include<stdio.h> int main() { int a = 10, b; b = (20, a); // b = a printf(" b = %d ", b); getchar(); return 0; } |
chevron_right
filter_none
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Comma in C and C++
- Operands for sizeof operator
- Copy constructor vs assignment operator in C++
- Self assignment check in assignment operator
- Rules for operator overloading
- Result of comma operator as l-value in C and C++
- C/C++ Ternary Operator - Some Interesting Observations
- Is assignment operator inherited?
- When should we write our own assignment operator in C++?
- Default Assignment Operator and References
- Can we use % operator on floating point numbers?
- Scope Resolution Operator Versus this pointer in C++?
- Set a variable without using Arithmetic, Relational or Conditional Operator
- Placement new operator in C++
- Operator Overloading in C++



