[prog] C and curly braces - question of style?
Jacinta Richardson
jarich at perltraining.com.au
Mon Aug 23 11:10:54 EST 2004
In my experience there are way too many variations of placements of
curly braces. However they can be reduced into roughly three groups:
1. curlies aligned with construct keyword. ie:
while ( something > 0 )
{
if( somethingelse )
{
for ( i = 1; i < something; i++)
{
some code;
some more code;
}
}
}
2. starting curly on key line, ending aligned with construct keyword. ie:
while ( something > 0 ) {
if( somethingelse ) {
for ( i = 1; i < something; i++) {
some code;
some more code;
}
}
}
3. curlies aligned with indent level. ie:
while ( something > 0 )
{
if( somethingelse )
{
for ( i = 1; i < something; i++)
{
some code;
some more code;
}
}
}
In my opinion either 1 or 2 is fine and learning to change between the
two is easy. 2 has the advantage that less whitespace is used, 1 has
the advantage (at least for beginners) that it's really easy to see both
curlies. I started off with style 1 and but now tend to mostly use 2.
Too much maintenance of other people's code.
Also in my opinion, anyone who uses 3 should be forced to change, or
perhaps shot ;) (joking). I'm very glad that only a few people do it.
My biggest issue with this one is that everyone who uses either format 1
or 2 expect that the close curly will be (in this case) on the left
margin. Not having it there will have these programmers assume that its
missing and put it in. In my experience (when teaching C) most students
who adopted the 3rd style here had greater difficulty debugging their
programs than the others because of these expectations (which they often
had too) about the final curly.
But as someone else has said, whichever you choose *be consistent*. In
particular use a consistent indent level. One tab, or x many spaces...
Don't indent in some places and not in others.
Consistency means that if you have to edit someone else's code use the
style they use. Unless they don't use a clear style - in which case
grab one of the good indentation tools and run it over their code to
make it bearable. :)
Indentation and consistent bracing is a huge step towards minimising
obvious syntax errors and spending more time coding rather than debugging.
All the very best,
Jacinta Richardson
--
("`-''-/").___..--''"`-._ | Jacinta Richardson |
`6_ 6 ) `-. ( ).`-.__.`) | Perl Training Australia |
(_Y_.)' ._ ) `._ `. ``-..-' | +61 3 9354 6001 |
_..`--'_..-_/ /--'_.' ,' | contact at perltraining.com.au |
(il),-'' (li),' ((!.-' | www.perltraining.com.au |
More information about the Programming
mailing list