Basic but complex syntax in c

The base foll code on gcc 3 compiler outputs.

But when I replace {} with () , then it gives 4

  int i={3,2,4};printf("%d",i); 

Can someone explain this behavior? The operator follows the left, but this is not the case with {} .

+4
source share
1 answer

When you use {3,2,4}, you use scalar initialization, but you provide more elements than you need. This will cause a warning by the compiler, but yes, it will compile and execute, and the first element in scalar initialization will be assigned to the variable i.

When you use (3,2,4), you mainly use the comma operator (brackets are needed because you are initializing the variable). The comma operator evaluates the first operand and discards the result, then computes the second operand and returns the result. So here you are evaluating 3, discarding it, then evaluating 2, returning it (this return value is used as the left operand of the second comma) and finally evaluating 4 and returning it, so 4 is assigned to the variable i.

Here's another interesting operation:

 int i; i = 3,4; printf("%d\n",i); 

This will print 3, because the first i = 3 will be evaluated (since this is the left operand of the comma), and its result will be discarded. Then 4 will be evaluated and its result will be returned, but will not be assigned to a variable.

And to make things more interesting:

 int i,j; j = (i = 3,4); printf("%d %d\n",i,j); 

This will print "3 4". In other words, everything that I described above will happen, but when grade 4 is returned, it will now be assigned to j.

+22
source

Source: https://habr.com/ru/post/1445972/


All Articles