Home > Net >  C incrementation and variable declaration
C incrementation and variable declaration

Time:11-04

I have this question for a practice test in C that I don't understand. Show the output of the following program

x = y = 3;
y = x  , x  ;
printf("x = %d, y = %d\n", x, y);

Answer: 1 x = 5, y = 3

I dont understand what

x  , x   

Does x mean to implement the value of x into y then add one to it, but why is there a comma ? Would it just first add the value of x in y, and do x=x 1 twice?

I tried putting it in a compiler, found some struggles.

CodePudding user response:

In this statement:

y = x  , x  ;

It contains both the assignment operator and the comma operator as well as the postfix increment operator. Of these the postfix increment operator has the highest precedence followed by the assignment operator, then the comma operator. So the expression parses as this:

(y = (x  )), (x  );

The comma operator first evaluates its left operand for any side effects and discards the value of that operand. There is a sequence point here before it then evaluates its right operand, which means evaluating left side and all side effect are guaranteed to occur before those on the right side.

So let's first look at the left operand of the comma operator:

y = (x  )

The subexpression x evaluates to the current value of x and increments x as a side effect. At this point x has the value 3, so y gets assigned the value 3 and x is incremented to 4.

Now for the right side:

x  

Since x currently has the value 4, it is incremented to now contain the value 5.

So at the end x is 5 and y is 3.

CodePudding user response:

There is a wikipedia page explaining the comma operator in C and C : https://en.wikipedia.org/wiki/Comma_operator

It basically evaluates the two expressions left-to-right and returns the value of the second one.

Here you can see the precedence of operators in c : https://en.cppreference.com/w/cpp/language/operator_precedence

The comma operator has the lowest precedence.

In your example. The first line sets both x and y to 3. The second line increments x twice: x , x . However, since the assignment operator has higher precedence than the comma operator, y gets the value returned by the first increment. The statement is evaluated as (y = x ), x . The first x is executed and x gets the value of 4 and returns 3. This value is assigned to y: y = x . Then, the last x is evaluated and x gets the value 5.

  • Related