Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using comma in expression and assigning it to variable

Tags:

c

Please explain this block of code:

void main()
{   
    int t,
        a = 5,
        b = 10,
        c = 15;  
    t = (++a && ++b, ++a), ++a || ++c;   // need explanation for this line
    printf("%d  %d  %d %d", t, a, b, c);
}
like image 758
kavi Avatar asked Dec 09 '22 15:12

kavi


2 Answers

The comma operator returns the result of its second operand, and the || operator will short circuit. So what happens in this case is:

  1. ++a is evaluated, a is now 6.

  2. Since the result of (1) was non-zero, the right side of the && is evaluated. That means ++b, so b becomes 11.

  3. (1) and (2) are the left side of a comma operator, so the result of the && is discarded. (it's 1, if that matters to you).

  4. The ++a on the right side of the first , is evaluated. a is now 7.

  5. the assignment to t takes place - t is now 7, the result of the first comma operator.

  6. All of that was the left side of another comma operator, so the result (7) is discarded. Next ++a is evaluated. a is now 8.

  7. Since a is not 0, the || short circuits, and the ++c isn't evaluated. c stays 15.

Results: t is 7, a is 8, b is 11, and c is 15. The printf statement outputs:

7  8  11 15

Overall, this code would be easier to understand if you just wrote:

++a;
++b;
t = ++a;
++a;

Which has precisely the same behaviour.

like image 103
Carl Norum Avatar answered Dec 11 '22 11:12

Carl Norum


Execution ->

  t = (++a && ++b, ++a), ++a || ++c;  // () Priority
      ^
  t = (++a && ++b, ++a), ++a || ++c;  // ++a -> a = 6
        ^
  t = ( 6 && ++b, ++a), ++a || ++c;   // ++b -> b = 11
               ^
  t = ( 6 && 11 , ++a), ++a || ++c;   // 6 && 11 -> 1
           ^          
  t = ( 1 , ++a), ++a || ++c;         // ++a -> a = 7
            ^          
  t = ( 1 , 7), ++a || ++c;          // (1,7) -> 7 ... Comma operator has less priority 
          ^          
  t = 7, ++a || ++c;                //  (t = 7), ++a || ++c; ...Assigned value to t... Comma operator has less priority 
    ^
  ++a || ++c;                       // ++a -> a = 8
   ^          
  8 || ++c;                        //  8 || ++c -> 1 ...as 1 || exp -> 1...Logical OR skip next part if 1st exp is true  
    ^

Finally ->

t = 7
a = 8
b = 11
c = 15 
like image 31
Navnath Godse Avatar answered Dec 11 '22 11:12

Navnath Godse