I tried the following code in gcc:
#include<stdio.h>
int main()
{
int a=3,2,1;//////////////////////ERROR!//////////////////////////
printf("%d", a);
return 0;
}
I expected it to compile successfully as:
Then, the value of the integer variable a should have been 1 right? Or is it 3?
And why am I getting this error when I try to execute this program?
error: expected identifier or '(' before numeric constant
That's parsed as a three-part variable declaration, with two invalid variables.
You need to wrap the entire initializer in parentheses so that it's parsed as a single expression:
int a=(3,2,1);
If you separate the initialization from the declaration, you may get what you expected:
int a;
a = 3, 2, 1; // a == 3, see note bellow
or
int a;
a = (3, 2, 1); // a == 1, the rightmost operand of 3, 2, 1
as your original command is syntactically incorrect (it is the declaration so it expected other variables to declare instead of numbers 2
and 1
)
Note: All side effects from the evaluation of the left-operand are completed before beginning the evaluation of the right operand.
So
a = 3, 2, 1
which are 3 comma operators a = 3
, 2
and 1
are evaluated from left to right, so the first evaluation is
a = 3, 2
which result 2 (right-operand) (which is by the way not assigned to any variable, as the value of the left-operand a = 3
is simply 3
), but before giving this result it is completed the side effect a = 3
of the left-operand, i. e. assigning 3
to variable a
. (Thank AnT for his observation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With