Jump to content

  • Log In with Google      Sign In   
  • Create Account


if statement in for loop, brackets needed?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
32 replies to this topic

#1 cozzie   Members   -  Reputation: 1593

Like
0Likes
Like

Posted 10 February 2013 - 07:52 AM

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?



Sponsor:

#2 dmatter   Crossbones+   -  Reputation: 3044

Like
9Likes
Like

Posted 10 February 2013 - 08:10 AM

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.

#3 cozzie   Members   -  Reputation: 1593

Like
0Likes
Like

Posted 10 February 2013 - 08:27 AM

Thank for the reply/ info.

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



#4 L. Spiro   Crossbones+   -  Reputation: 13396

Like
14Likes
Like

Posted 10 February 2013 - 08:49 AM

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


Edited by L. Spiro, 11 February 2013 - 04:43 PM.

It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#5 rip-off   Moderators   -  Reputation: 8165

Like
6Likes
Like

Posted 10 February 2013 - 08:50 AM

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.



#6 Álvaro   Crossbones+   -  Reputation: 13010

Like
3Likes
Like

Posted 10 February 2013 - 09:19 AM

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();
}


#7 Wyrframe   Members   -  Reputation: 731

Like
0Likes
Like

Posted 10 February 2013 - 09:30 AM

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.


(( This email has been quad-ROT13 encrypted. Reading it violates the DMCA. ))
(( 我说很少的汉语,还我的语法平庸, but at least I'm UNICODE-compliant. ))


#8 Ectara   Crossbones+   -  Reputation: 2931

Like
1Likes
Like

Posted 10 February 2013 - 09:51 AM

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.

#9 SiCrane   Moderators   -  Reputation: 9574

Like
0Likes
Like

Posted 10 February 2013 - 10:18 AM

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.

#10 Buster2000   Members   -  Reputation: 1639

Like
1Likes
Like

Posted 11 February 2013 - 02:54 AM

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.



#11 Álvaro   Crossbones+   -  Reputation: 13010

Like
5Likes
Like

Posted 11 February 2013 - 05:36 AM

Well, the only protection against idiotic programmers is better hiring and firing decisions. Bracketing conventions won't do. smile.png

#12 wintertime   Members   -  Reputation: 1651

Like
0Likes
Like

Posted 11 February 2013 - 05:37 AM

For me brackets or not seems just like a matter of style. If there are none and you add a second line, surely you should know you also need to add brackets.

But putting the body on the same line as the if is annoying if you happen to want to put a breakpoint there or single step the if, as you cant easily see then if the body was actually run.


Edited by wintertime, 11 February 2013 - 05:37 AM.


#13 Olof Hedman   Crossbones+   -  Reputation: 2767

Like
1Likes
Like

Posted 11 February 2013 - 06:47 AM

There is only one case where I feel its acceptable to omit braces.

It's for one line tests with simple expressions like this:

 

if(!some_object) some_object = new SomeClass();

 

If you want to add a second line, you have to start with adding a line break, and at that point, it's very obvious that you need to add brackets too. 

Even with stress levels high.

 

 

For me brackets or not seems just like a matter of style. If there are none and you add a second line, surely you should know you also need to add brackets.

Well, the only protection against idiotic programmers is better hiring and firing decisions. Bracketing conventions won't do.

 

Easy to say until that day you sit there with the deadline looming over your head, with stress levels at max, trying to fix that last show stopper bug.

The "just going to add some print out" happens very easily... And you really dont want to spend even 5 minutes with something like that, totally breaks your flow.

 

Clean and consistent code = less bugs and frustration

always.


Edited by Olof Hedman, 11 February 2013 - 06:49 AM.


#14 Bregma   Crossbones+   -  Reputation: 5054

Like
2Likes
Like

Posted 11 February 2013 - 07:28 AM

I have spent decades coding in C-like languages.  I have seen a significantly disproportionate number of software error arising from not using braces in control statements than from (almost) any other construct.  The 'other construct' is mistaking '=' for '==' in comparisons, but that's less easily avoided.

 

The problem doesn't come from writing new code.  The problem comes from maintaining existing code.  Remember that all code is existing code the moment you're finished typing it.

 

I have worked on projects in which the formalized and enforced coding style dictates that a single line in a control construct should never use braces, likely in an attempt to save on electrons.  With one significant exception, every such project has had a higher bug rate and higher maintenance cost.  The one exception has a very large automated test suite (which takes hours to run) but is under very restricted maintenance, since it's a standard library with strongly defined functionality and wide distribution.

 

There are, of course, strong opinions on the aesthetic of brace usage in coding style.  Such opinions are significantly more important than practical issues such as minimizing maintenance costs or maximizing software reliability.


Stephen M. Webb
Professional Free Software Developer

#15 Álvaro   Crossbones+   -  Reputation: 13010

Like
3Likes
Like

Posted 11 February 2013 - 09:29 AM

I have programmed in C-like languages for aboud 20 years now, 13 of them professionally. I have never ever seen a problem with the use of braces. So I don't think it's that important.

It could also depend on what editor you use. Emacs understands the level of indentation you are at, so when you go to add a second line to the `then' clause, the cursor will go to a place where it's obvious that you need braces.

I agree with everyone that the most clear style should be used. So use whatever you think is more clear.

#16 King Mir   Members   -  Reputation: 1968

Like
0Likes
Like

Posted 11 February 2013 - 11:07 AM

Ho boy, a bracketing convention debate.

 

My advice is to always use braces.

 

In practice, I add braces only when I need them, but don't remove them when the need disappears, such as if debug code is removed or the code is reformatted.

 

Also, I always use a newline after all if statements and non-empty loops. Empty loops get a pair of braces on the same line. 



#17 Ectara   Crossbones+   -  Reputation: 2931

Like
0Likes
Like

Posted 11 February 2013 - 11:17 AM

Empty loops get a pair of braces on the same line.


That's an interesting idea. I use empty braces on the same line for an empty function or class definition. My empty loops look like this:
while(*(src++) = *(dst++))

        ;

 

I guess I just feel like loop bodies should start on the next line, no matter what. I'm also strongly against semi-colon on the same line to prevent things like this:
for(;;);
{
//Why am I not executed as expected?
}


Edited by Ectara, 11 February 2013 - 11:17 AM.


#18 Buster2000   Members   -  Reputation: 1639

Like
1Likes
Like

Posted 12 February 2013 - 02:55 AM

I have programmed in C-like languages for aboud 20 years now, 13 of them professionally. I have never ever seen a problem with the use of braces.

 

I find that hard to belive that in 13 years of proffesional coding you have never once found a bug written by either you or by someone else that involved incorrect use of braces.

 



#19 Álvaro   Crossbones+   -  Reputation: 13010

Like
0Likes
Like

Posted 12 February 2013 - 06:57 AM


I have programmed in C-like languages for aboud 20 years now, 13 of them professionally. I have never ever seen a problem with the use of braces.

 
I find that hard to belive that in 13 years of proffesional coding you have never once found a bug written by either you or by someone else that involved incorrect use of braces.


I'm telling you, I can't remember one. As I said, emacs makes it very obvious if you are writing at the wrong level of indentation. Also, perhaps our testing procedures are good at catching that type of mistake.

#20 Cornstalks   Crossbones+   -  Reputation: 6974

Like
0Likes
Like

Posted 12 February 2013 - 08:32 AM

I have programmed in C-like languages for aboud 20 years now, 13 of them professionally. I have never ever seen a problem with the use of braces. So I don't think it's that important.

I have. Once. (though I've got much less experience than you). It was in the FFmpeg source code. Indentation levels indicated the else statement was part of a different if block, but actual control flow was otherwise. The actual logic ended up being correct, but anyone reading the code was likely to misread the code (like I did initially) because of incorrect indentation levels and a complete lack of braces. That was a fun day.


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS