in reply to Re^4: if/else syntax
in thread if/else syntax

The compiler understands it fine.

Not true. How can the compiler understand it fine when C doesn't define it

if(a) if(b) c(); else d();

means

if(a) { if(b) c(); else d(); }

or

if(a) { if(b) c(); } else d();

Both are right. Neither is right.

I don't know if that was fixed in recent versions of C.

There's actually no ambiguity in the C syntax for your example.

That's not true either. You contradict yourself in the next sentence. You write code for both people and for compilers to read. Ambiguity for either is still ambiguity.

Anyway, the topic wasn't ambiguity but (the avoidance of) traps. C's if/else definitely has pitfalls.

Replies are listed 'Best First'.
Re^6: if/else syntax
by massa (Hermit) on Jun 26, 2009 at 17:33 UTC
    Sorry, but you are wrong. Since immemorial times and K&R release 1,
    if(a) if(b) c(); else d();
    is DEFINED as
    if(a) { if(b) c(); else d(); }
    But, this does not mean there is no ambiguity. It's just plain wrong to assume things without the braces because software changes constantly. So, one day you have
    if( a ) if( b ) c(); else d(); else e();
    and then you see some reason for the else d(); to go away, and you stay with
    if( a ) if( b ) c(); else e();
    That does not do what you intended and you can be looking for this bug in another place kilometers/miles away (in the code) because you left out some initialization done by e(); etc etc.

    IOW: You could do that -- because it's really well-defined behaviour for the C language --, but it does not mean you should.

    []s, HTH, Massa (κς,πμ,πλ)
Re^6: if/else syntax
by gwadej (Chaplain) on Jun 29, 2009 at 13:34 UTC

    I'd suggest you check your standard again. It was defined in K&R and in the ANSI/ISO standard.

    Update: Just to make sure I hadn't misremembered, I dug out the ISO C++ standard (which is all I have handy at the moment.) Section 6.4.1 addresses this issue.

    In the second form of if statement (the one including else), if the first substatement is also an if statement then that inner if statement shall contain an else part.

    There was also no contradiction in my later statement. The is no ambiguity in the standard (or compiler) interpretation. But there is a problem with the way the programmer will read it. This is why Perl made the braces mandatory and Python made the indention mandatory.

    G. Wade