if statement in for loop, brackets needed?

Started by
31 comments, last by Nicholas Kong 11 years, 2 months ago

Hi,

Just a simple question, with a nice opportunity to clean my code :)

I'm not sure when I need to use brackets in a for loop, depending on the code that needs to be executed for each iteration.

Example, I have:


for(mat=0;mat<mNrMaterials;++mat) 
{	
	if(materials[mat]) ++mEffect[fx].nrMaterials; 
}

Would the result be the same if I use:


for(mat=0;mat<mNrMaterials;++mat) 
	if(materials[mat]) ++mEffect[fx].nrMaterials; 

I know that I can leave the brackets out if I just have one line of code for each iteration, like:


for(int i=0;i<5;++i)
  something[i] = i*2;

Anyone?

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Advertisement
Yes the two are the same. Under the for-loop there is only one thing: an if-expression. Which itself has a body of just a single expression. So no curly brackets needed at all.

Obviously this is a matter of personal taste, but I dislike bracket-less scopes. I always put curly braces even if there is only one expression in the body. Clearly formatted code is more important to me than compact code. It would be too easy for someone in a rush to stick their cursor on the end of that line, hit enter, see an indented cursor and begin typing new code thinking that it will all be executed as part of the for loop.

Thank for the reply/ info.

Always a difficult balance between compact and clean code, good to know that functionally both works.

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Clean your code by always using braces even if they are not required by the syntax.

Consistent code is clean code.
Omitting braces “just because you can” is inconsistent. It is a sign you seek to put forth the minimal effort allowed by the syntax rather than to just keep things the same everywhere.
It unnecessarily puts you or those maintaining your code later at risk of hard-to-spot bugs.


int iSum = 0;
for ( int i = 0; i < 20; ++i )
    iSum += i;

“It works. Humm, but I want to see what the value of iSum is on each iteration.”


int iSum = 0;
for ( int i = 0; i < 20; ++i )
    cout << iSum << endl;
    iSum += i;

“What it always prints 0 and my algorithm broke too, WTF!?”

There is just no need for this kind of risk.
As mentioned already, clearer code is more important than compact code.

Omitting braces for the sake of syntactical exceptions just doesn’t make sense.


L. Spiro

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

The typical example used to illustrate the difficulty of not using braces is this:

if( foo )
    if( bar )
        actionA();
else
    actionB();

The indentation hints that the else is paired with the "foo" conditional, but the parser will ignore this and pairs it with "bar". Almost all professional style guides I've seen require braces for loops and conditionals.

My taste on this has evolved over the years, but I have settled on using curly braces when there is more than one line in the body, even if it is technically only one thing.

for (int mat=0; mat<mNrMaterials; ++mat) {
  if (materials[mat])
    ++mEffect[fx].nrMaterials; 
}

if (foo) {
  if (bar)
    actionA();
  else
    actionB();
}

I use unbraced forks only for if-wrapped return, continue, break, and throw statements, because those don't have "else" forks; any subsequent code is an "else" after that.

But, I also tend to write very dense loops, frequently without an actual body, so sometimes the body of my loops ends up being a single semicolon, ie

for(int i=0, j=arraylength-1; i<j; array[j--]=array[i++]) ;

And that just becomes more unreadable when I waste essentially blank lines putting empty braces on the following couple lines.

RIP GameDev.net: launched 2 unusably-broken forum engines in as many years, and now has ceased operating as a forum at all, happy to remain naught but an advertising platform with an attached social media presense, headed by a staff who by their own admission have no idea what their userbase wants or expects.Here's to the good times; shame they exist in the past.

I have settled on using curly braces when there is more than one line in the body


I'll throw another vote in this pile. I use no curly braces when the statement does not have its own block scope, and when it can fit cleanly on one line. If it requires two, I put braces on it. Since I put if statements on a separate line from what is executed conditionally, then that means that that is enclosed in braces, too. I do agree that extra braces reduces the possibility of human error; I may consider doing it all the time at a later point. In effect, I use no braces when the block looks concise enough that it can be readily understood as being the sole statement of the block, and that no more statements would be added. If I have to debug, I add braces, output the values, then remove braces when I remove the output code.

In my mind, where I parse the source linearly, a no-brace if statement gives me an explicit measure of what the conditional encompasses, and it looks aesthetically pleasing to my eye at how the simple things appear very obviously simple.

However, once I must team up with someone that is prone to human error in these kinds of places, I'd probably opt to ensure that we aren't each other's downfall.
My rule for if and brackets is if there is an else then brackets need to go on both halves and an if containing an if or a loop statement requires brackets on the outermost if. So

// fine
if (a) foo;

if (a) if (b) foo; // no good instead do:
if (a) {
  if (b) foo;
}

if (a) for (;;); // also bad, instead:
if (a) {
  for (;;);
}

// fine
if (a) {
  foo;
} else {
  bar;
}
Similarly, for loop statements a loop containing a loop or an if requires brackets.

My rule is to ALWAYS use braces no matter how little code is inside them. It is just a more secure way of coding. There are already resons mentioned above. But my personal favorite was a senior coder (who was also a complete fuckwit) I worked with a couple of years ago made it a rule that single lines should not have brackets. He also had a list of debug macros that he used.

Instead of disableing the macros when he did a release he just did a grep and replace to comment out all the macros.

So we ended up with:

<get some data>

if(<a problem with data>) //<commented out macro here>

<do processing on the data>

This pattern by the way he had used in several hundred places throughout the project. Then he blamed the rest of us for it not working even though we had told him his code was shocking during every single code review.

This topic is closed to new replies.

Advertisement