Reputation: 8610
I have a C code ,which uses simple comma operators
main()
{
int a= 1,2,3;
printf("%d",a);
}
Now when i compile got an error while same program with little modification runs fine
main()
{
int a;
a= 1,2,3;
printf("%d",a);
}
Why is it so?
Upvotes: 0
Views: 140
Reputation: 38025
When using variable initialization form, the comma does not act as the same operator. It is a special short-hand form for declaring multiple variables on the same line and thus requires its own syntax.
Thus in the statement int a = 1, 2, 3
, the comma is actually being interpreted differently than in the statement a = 1, 2, 3
.
The former is a syntax error because it doesn't meet the multiple variable declaration form. The second is valid syntax, but as others have pointed out is rather pointless because the statements 2;
and 3;
while syntactically correct, do nothing.
See this article on Wikipedia.
Upvotes: 0
Reputation: 25873
In the first case, the error is raised because the compiler is not able to differentiate if you pretend to declare several variables or assign several values.
int a= 1,2,3;
Did you mean int a; a = 1, 2, 3
, or int a = 1, int 2, int 3
? Compiler cannot tell from context (even if 2 or 3 are not legal variable names).
This ambiguity does not exist in the second case, hence no error (but warnings issued anyway).
PS: it's int main()
not void main()
.
Upvotes: 6