Consider the following C programs.
The above program fails in compilation, but the following program compiles fine and prints 1.
And the following program prints 3, why?
In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator. (See this for more details).
Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3” becomes equivalent to “(a = 1), 2, 3”. That is why we get output as 1 in the second program.
In PROGRAM 3, brackets are used so comma operator is executed first and we get the output as 3 (See the Wiki page for more details).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Operators in C | Set 1 (Arithmetic Operators)
- sizeof operator in C
- Interesting facts about Operator Precedence and Associativity in C
- Difference between ++*p, *p++ and *++p
- To find sum of two numbers without using any operator
- Scope rules in C
- Result of comma operator as l-value in C and C++
- Order of operands for logical operators
- Increment (Decrement) operators require L-value Expression
- Precedence of postfix ++ and prefix ++ in C/C++
- Modulus on Negative Numbers
- Comma operator should be used carefully
- Comma in C and C++
- Evaluation order of operands
- Operands for sizeof operator