braces needed?

From: Jason (jason.carney1_at_btinternet.com)
Date: 01/31/04


Date: Sat, 31 Jan 2004 02:02:04 +0000 (UTC)

Programming recently I was the habit of leaving out the braces on if
statements if the branch only applied to a single line, assuming it would
all work and be equivalent to "if(condition) { statement; }" I implemented
an algorithm and it did not work for a while and when i tracked the problem
down it was as if a certain action was not being done from one of these if
statements that did not have a brace, so I placed all if statements in
braces and it worked as expected. This was not a result of misunderstanding
on my part such as including 2 statements under the braceless if and I know
indentation is not important, the statements were usually all on one line
anyhow.

It appeared to work ok when I first started doing it, but not when there was
a few in a row or near each other inside while loops and such like. In some
parts of my code I have neglected to change them to braces without any
problems, confusing me.

I also sometimes feel the desire to omit braces from while and for loops
because i find them irritating and like to shorten my code. Am I able to
avoid braces or not? Is it guaranteed to work or do different compilers
produce different results? If I have code that works perfectly now and all
I do is remove braces from single statement if, for and while loops, is it
guaranteed to make no difference or am I naive to some other potential
problem?

thanks for clarifying.



Relevant Pages

  • Re: braces needed?
    ... > braces and it worked as expected. ... > a few in a row or near each other inside while loops and such like. ... I have never seen a professional coding standard that did not require ...
    (comp.lang.cpp)
  • Re: Seriously struggling with C
    ... This semester I have started a course in C programming. ... This is my thought process on loops: ... Not using the braces of a compound-statement for while's and if-else's when ...
    (comp.lang.c)
  • Re: braces needed?
    ... > braces and it worked as expected. ... > a few in a row or near each other inside while loops and such like. ... macros particularly debug ones or ones requiring a local variable ...
    (comp.lang.cpp)
  • Re: strcpy warning
    ... >> where the whole thing is short enough to fit on one line. ... >> habit I picked up from Perl, which requires the braces, but I find it ... > real program, I would almost always put braces around the body of ...
    (comp.lang.c)