views:

26

answers:

1

I'm used to write code (in C, Perl, or any language with curly brackets) like:

Loops:

for (int i = 0; i < 10; i++) { // <-----
    ...
}

Conditions:

if (i == 10) { // <-----
    ...
}

Main:

int main () { // <-----
    ...
}

Wherein I place the opening curly bracket right after the closing parenthesis. Yet, I see some templates (like in MSVC++):

int main () 
{ // <-----
    ...
}

Wherein the opening curly bracket is placed below.

I know that this doesn't affect the code on compilation, but I would like to ask this for code readability and for code documentation. What should I follow? The one I'm used to? Or the one compilers suggests? I would like to know which one is better.

Bonus Question: How about the space between the function name and the opening parenthesis? Should there be a space?

int main() or int main ()?

Thank you.

+1  A: 

In Code Complete, Steve McConnell argues that, of the options you posted, the original is best:

if (i == 10) { // <-----
    ...
}

The reason being that it gives a better indication of the structure of the code. This can be seen best if you check it out based on the code outline:

xxxxxxxxxxxxx
    xxxxxx
    xxxxxx
x

vs

xxxxxxxxxxxxx
x
    xxxxxx
    xxxxxx
x

In the first example (he argues), it's clearer to see what code goes with what block.

personally I think there's some validity to that, but my reasons for choosing that style are because it's less wasteful for single line statements:

if(x) {
    y=z;
}

vs

if(x)
{
    y=z;
}

Of course (in C# at least), you can always just leave off the curly brackets in that situation, which I used to do, but that leads to it's own problems when the code gets extended, for example:

if(x)
    x=z;
    w++;

In summary, it doesn't really matter that much, but you should definitely always do it the first way, even if it annoys your colleagues. ;-)

Grant Crofton
Thanks for your answer! greatly appreciated, and how about the bonus question I posted, what do you think of that?
Ruel
Hadn't really thought about it before - I think it looks better without a space when there are no parameters, but with a space when there are, so a tricky one! If I had to pick I'd say leave a space, it probably looks better in general, and also matches if statements etc (which I think are better with a space).
Grant Crofton
Thanks for that! :)
Ruel