I like to do this:
1 2 3 4 5 6 7 8
|
if (condition) {
//do stuff
}
for (init ; endcondition ; increment) {
}
|
It helps newbies because there is less temptation to do this:
1 2 3 4 5 6 7 8 9 10
|
if (condition) ;
{
//do stuff
}
for (init ; endcondition ; increment) ;
{
//do stuff
}
|
I mean, hopefully they are less likely to put the semicolon between the condition and the opening brace. Errors like that are hard to see. It also saves 1 line - not that that matters a damn.
I always use braces, even when there is only 1 statement following - this will save you one day when adding more code.
I generally dislike do loops, but if one insists on using them, put the while condition on the same line as the closing brace:
1 2 3 4
|
do {
//stuff
} while (condition);
|
I almost always find a way to write a do loop as a while or for loop.
If you find yourself with a while loop with a null statement - put it on it's own line with a comment:
1 2
|
while (condition)
; //null statement
|
Always make use of functions - there is a bit of a rule that functions should not be more than 80 lines - presumably so one can print it on 1 A4 page. Functions can be handy even if there are 3 or 4 lines long. Especially in the body of a for loop.
Prefer to use switch statements when the variable is a constant int or char, rather than a load of else if's. Always have a
default:
clause to catch bad input
Use arrays & for loops rather than lots & lots of if's.
I really hate these constructs - just UGLY:
1 2 3
|
if (a != b && a != c && a != d && a != d) {
}
|
Much better to use a switch for this.
Here is another handy loop:
1 2 3 4 5 6 7 8 9 10
|
bool Quit = false;
while(!Quit) {
//get input
//use the toupper function to make testing easier for input like y n or q
// stuff maybe a switch
//user wants to quit
Quit = true;
}
|
code continues after the while loop.
There you go hope that helps & have fun !!