Working on GCC compiler, with following two cases of operators in C program, observed different behaviors.
1.
int i = 1,2,3;
printf("%d",i); // this will give compile time error
And,
2.
int i;
i = 1,2,3;
printf("%d",i); // Its output will be 1.
In 1st case compiler gave error "error: expected identifier or ‘(’ before numeric constant". And in second case, no errors, and output is 1. Can anybody explain here the compiler behavior in both the cases in detail? How does compiler interpret both statements?
Thanks in advance for your inputs.
In the first case the comma separates declaration and initialisation of several variables of the same type:
int i = 1, j = 2, k = 3;
You can add parentheses to tell the compiler it's an expression.
int i = (1, 2, 3);
If you combine them, it's easier to see why the comma is ambiguous without parentheses:
int i = (1, 2, 3), j = 4, k = 5;
In the second case the comma separates 3 expressions.
(i = 1), 2, 3
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