How "else" works in "1 line if" in C?

Viewed 59

I searched it up but I haven't found the answer to this, so I saw a piece of code as follows,

int a=0, b=1, c=0;
if (a)
if (b && c) puts ("yes");
else puts ("no");

I know that we may not use {} if the statement is only 1 line like if (true) //something;, so I assumed that else belonged to if (a) but when I run the code, no doesn't show up, at first I thought it's the same as

if (a) if (b && c) puts ("yes");
else puts ("no");

or,

if (a)
    if (b && c) puts ("yes");
else puts ("no");

But instead, it is

if (a)
{
    if (b && c) puts ("yes");
    else puts ("no");
}

Why that else is paired with the inner if instead of the outer if?

2 Answers

Why that else is paired with the inner if instead of the outer if?

That's how it works, else gets paired with the closest if. It helps if you use correct indenting, either by hand or automatically by your IDE:

if (a)
    if (b && c) 
        puts ("yes");
    else 
        puts ("no");

From this C11 Draft Standard, §6.8.4.1, paragraph #3:

3 An else is associated with the lexically nearest preceding if that is allowed by the syntax.

In your case, the "nearest preceding if" statement is if (b && c) puts ("yes");.

Related