Can someone explain output stepwise? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone explain output stepwise?

#include <stdio.h> int main() { int a=(1, 2,3); int b=(++a, ++a, ++a) ; int c=(b++, b++, b++) ; printf ("%d, %d, %d", a, b, c) ; /* output is 6,9,8 */ return 0; }

23rd Nov 2018, 2:20 PM
Akshay Kumbhar
Akshay Kumbhar - avatar
5 Answers
+ 9
**Comma operator** The comma operator expression has the form lhs , rhs where lhs - any expression rhs - any expression other than another comma operator (in other words, comma operator's associativity is left-to-right) First, the left operand, lhs, is evaluated and its result value is discarded. Then, a sequence point takes place, so that all side effects of lhs are complete. Then, the right operand, rhs, is evaluated and its result is returned by the comma operator as a non-lvalue. ~~~~~~~~ int a = ((1, 2),3); // a = 3 int b = ((++a, ++a), ++a) ; // a = 6, b = 6 int c = ((b++, b++), b++) ; // b = 9, c = 8 ____ https://en.cppreference.com/w/c/language/operator_other#Comma_operator
23rd Nov 2018, 2:31 PM
Babak
Babak - avatar
+ 6
"Else the assignment operator (=) would take precedence" In the case of a declarator the compiler issues an error int n = 2,3; // error, comma assumed to begin the next declarator
23rd Nov 2018, 2:43 PM
Babak
Babak - avatar
+ 5
C++ Soldier (Babak) true! Assignment takes precedence, and that's why it throws the error. We won't get any value. I was careless. :)
23rd Nov 2018, 2:50 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 5
A variable name cannot start with a number lol
23rd Nov 2018, 4:10 PM
AZTECCO
AZTECCO - avatar
+ 2
Also note that the parentheses are important. Else the assignment operator (=) would take precedence, and the values would be different.
23rd Nov 2018, 2:38 PM
Kishalaya Saha
Kishalaya Saha - avatar