I know a statement like the following (commas in place of semicolons) looks odd:
if(a < b) printf("Hello\n"), a+=5, b/=5, printf("%d,%d", a, b);
But it works perfectly fine and I had read that it's because comma
here acts as a sequence point. I can understand this. But I just fail to understand why the following fails then, where I have used a else
as well:
if(a < b) printf("Hi\n"), else printf("Bye\n"), a+=5, b/=5, printf("%d,%d", a, b);
It gives the error expected expression before 'else'
.
Why does the second statement gives error?In the first statement, we saw that comma
acts as a sequence point.Then why it doesn't act so before else
?What's special about the second case that causes error?Here's my full program:
#include <stdio.h>
int main(void)
{
int a=30, b=45;
//if(a < b) printf("Hello\n"), a+=5, b/=5, printf("%d,%d", a, b); // Works well
if(a < b) printf("Hi\n"), else printf("Bye\n"), a+=5, b/=5, printf("%d,%d", a, b);
}
The comma operator expects an expression and the else
part of an if
else
construct isn’t an expression. Thus a comma followed by the keyword else
is a syntax error.