Question

I know a statement like the following (commas in place of semi-colons) 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); 

}
Was it helpful?

Solution

The comma operator expects an expression and the else part of an if else construct ain't an expression. Thus a comma followed by the keyword else is a syntax error.

OTHER TIPS

Imagine, that:

(a, b)

is translated to:

{
    a;
    return here b;
}

In this case, return here means "insert in place of this expression". And indeed, , acts as a sequence point.

Then,

if (a<b) printf("Hello\n"), a+=5, b/=5, printf("%d,%d",a,b);

would look like:

if (a<b)
{
    printf("Hello\n");
    a += 5;
    b /= 5;
    return here printf("%d, %d", a, b);
}

But

if(a<b)printf("Hi\n"),else printf("Bye\n"),a+=5,b/=5,printf("%d,%d",a,b);

Would look like:

if (a < b)
{
    printf("Hi\n");
    else printf("Bye\n");
    a += 5;
    b /= 5;
    return here printf("%d, %d", a, b);
}

And the else inside does not make any sense. That's why compiler complaints.

In other words, , in C++ is an operator. So by the operator precedence,

if(a<b)printf("Hi\n"),else printf("Bye\n"),a+=5,b/=5,printf("%d,%d",a,b);

is interpreted as

if(a<b) ( printf("Hi\n"),else printf("Bye\n"),a+=5,b/=5,printf("%d,%d",a,b) );

Which clearly violates the C++ syntax rules.

Look at the correct syntax of IF-ELSE statement. Compiler expects semicolon to know that IF is ended. So you are basically trying to enter sub if-else statement into the first one, but without new if.

if(a>=18 &a <=64)printf("adult\n"); 
else if(a<=17)printf("minor\n"); 
else printf("senior\n");

So, either the curly brackets "{}" indicate the IF region, or if they are missing, IF statement valid until the first semicolon.

In 2nd case else is no having matching if, what is happening here is after printf("Hi\n"), when else arrives compiler looks for if i.e else should come only after terminated if statement. so it is giving error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top