I was trying to run following code and came across some results. Can somebody please explain:
int number = {12,13,14};
printf("%d",number);
Above code prints output as 12
. If I try to run the following code:
int number = (12,13,14);
printf("%d",number);
this prints output as 14
, but with following code it prints output as 12
:
int number;
number = 12,13;
printf("%d",number);
number = {12,13,14}
is scalar initialization, but you are providing more elements than what you should, compiler will throw a warning which, I assume, you have ignored and the first element 12 is assigned to variable number
.
When you use number = (12,13,14)
,
comma (,
) operator evaluates the first operand and discards the result, then evaluates the second operand and returns the result.
So here 12 is discarded and 13 is evaluated to 13 and returned. Now this returned 13 value is first operand for next comma operator.
Now, it will evaluate 13 to 13 and will discard this result 13 and will evaluate second operand i.e. 14 and will return the result as 14 which is assigned to variable number
.
When you do following
number = 12,13;
printf("%d",number);
This will print 12, because precedence of =
is greater than ,
so first number = 12
will be evaluated and =
return assigned value i.e. 12.
Now comma operator got two operands retured value of =
operation i.e. 12 and 13.
With comma operator 12 will be evaluated as 12 and discarded. 13 is evaluated and returned.
Returned to? Nobody. Not assigned to number
because assignment is already executed.
So number = 12,13;
looks like (number=12),13;
Try this as well.
int num1,num2;
num2 = (num1 = 13,14);
printf("%d %d",num1,num2);
This will print 13 14
as per the argument given for earlier code output.