if (e1) return e2; [else] s1;

Dave Straker daves at hpopd.HP.COM
Sun Mar 25 19:56:24 AEST 1990


/ hascall at cs.iastate.edu (John Hascall) /  8:50 pm  Mar 23, 1990 /writes:
>
>    Ok, style mavens, which is "better":
>
>    if (e1) return e2;                    if (e1) return e2;
>    else s1;                              s1;

I'd vote for the second one, unless the rest of the function is contained in
s1. Thus, 

     if (e1) return e2;
     else s1;
     s2;

..would be bad style, as s1 and s2 are both going to get done, and shouldn't
be separated. Using the 'else' is giving an explicit message 'there are two
choices here'. Not using 'else' means that s1 is something new, and has little
to do with what has gone before.

>
>---------------------------------------------------------------
>    I'm not sure which of the above is better, but I am sort of
>    "stuck on" the following convention:
>
>    if (e1) s1;        \
>      --or--            \
>    if (e1) {           | Does this seem reasonable?
>	s1;             | (ignoring whether or not the `{'
>    }                   | belongs on the next line or not)
>    --but never--       |
>    if (e1)             /
>	s1;            /
>
>Stylistically yours,
>John Hascall

I would never use the first version, as I prefer to keep one item per line.
The 's1' is easily lost to those not used to this sort of stuff (style rule
no. 1: Think Of The Reader).

The second version is putting a single statement into braces. I would do this,
as it is clear that this is a consequence of the 'if'. It also makes it easier 
to insert lines later. Also, if you have a programmable editor, you can program
'if' to automatically add the braces and position the cursor.

I actually prefer one of the other bracing styles, either 'Whitesmiths':

     if (e1)
     {
	 s1;
     }

or 'Allman' (the names came from an 'emacs' manual, BTW):

     if (e1)
	 {
	 s1;
	 }

I will admit to using Whitesmiths most often, as I was (duck) brought up
on Pascal, although it has several advantages over K&R, eg.

     if ( complex expression that wraps
	  to next line )
     {
	 statement;
	 statement;
     }

..is clearer where the block is than:

     if ( complex expression that wraps
	  to next line ) {
         statement;
         statement;
     }

However, Allman does this and is more consistent with single statement (no
braces) after the 'if' line, as it has the simple rule, 'after the 'if', indent 
the following statement. It also allows the statements of a function to start
in column 1. Look what happens if you do this with K&R or Whitesmiths:

int foo()
{

if (e1)
{
    s1;
}
}

ouch! braces at the same level.

Regards,

Dave (brace yourself) Straker



More information about the Comp.lang.c mailing list