[Tip] Style: using indenting and spaces
| Author |
Message |
wtd
|
Posted: Fri Oct 01, 2004 12:20 am Post subject: [Tip] Style: using indenting and spaces |
|
|
Second C++ tip of the night.
What
One of the keys to writing readable code is to properly use spacing and indentation.
Why
Readable code is easier to modify and debug. You will get better feedback from others as well if you need help. It will take others time just to figure out what your code is that they could otherwise spend figuring out what's wrong.
How
- Indent code in braces
Anywhere code falls between curly braces ( { } ), indent it with a single tab or three or four spaces. If you use spaces, do so consistently.
Wrong
| code: | int foo(int bar, int baz)
{
return bar * baz;
} |
Right
| code: | int foo(int bar, int baz)
{
return bar * baz;
} |
Wrong
| code: | if (wooble == 42)
{
doSomething();
}
else
{
doSomethingElse();
} |
Right
| code: | if (wooble == 42)
{
doSomething();
}
else
{
doSomethingElse();
} |
It Becomes more important...
When you have multiple levels of braces.
Wrong
| code: | int foo(int bar, int baz)
{
if (bar == baz)
{
if (bar < 42)
{
wooble();
}
else
{
fish();
}
}
else
{
ninja();
}
} |
Very very right
| code: | int foo(int bar, int baz)
{
if (bar == baz)
{
if (bar < 42)
{
wooble();
}
else
{
fish();
}
}
else
{
ninja();
}
} |
Use space around operators
All too frequently I see code that looks like:
| code: | int wooble=42;
float foo,bar,baz; |
This all perfectly valid syntax, but it flows so much better as:
| code: | int wooble = 42;
float foo, bar, baz; |
I've got my fingers so well-trained to type the method with spaces that the first one was actually hard to type, so don't worry that it'll save you time to omit the spaces.
Also, it won't make your program smaller.
This same principle can be applied to pretty much any operator.
Wrong
| code: | if (foo==bar)
{
wooblize();
} |
Right
| code: | if (foo == bar)
{
wooblize();
} |
Really wrong
| code: | if (foo==bar&&baz>wooble||ninja<=fish)
{
return freud;
} |
Right
| code: | if (foo == bar && baz > wooble || ninja <= fish)
{
return freud;
} |
Of course, the truth is that these guidelines apply to many languages, and following them will greatly aid you in writing and debugging programs, and especially in getting others interested. |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
|
|