Search code examples
cexpressionexecution

What is the execution logic of the expression in C?


Suppose I a couple of expression in C. Different outputs are provided.

int i =2,j;
j= i + (2,3,4,5);
printf("%d %d", i,j);
//Output= 2 7

 j= i + 2,3,4,5;
 printf("%d %d", i,j);
 //Output 2 4

How does the execution take place in both expression with and without bracket giving different outputs.


Solution

  • Comma operator works by evaluating all expressions and returning the last expression.

    j= i + (2,3,4,5);
    

    becomes

    j= i + (5); //j=7
    

    In the second expression assignment operator takes precedence over comma operator,so

    j= i + 2,3,4,5;
    

    becomes

    (j= i + 2),3,4,5; //j=4