braces needed?

J

Jason

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.
 
D

David Harmon

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?

It is guaranteed to work the same on all compilers. This part of the
language syntax has been well defined from the very beginning of C, and
it would be a huge shock to find a compiler that got it wrong.

The thing controlled by an "if" or "while" is conceptually a single
statement. Multiple statements with braces around them are considered a
single "compound statement". If you want, you can put braces around a
group of statements that have nothing to do with any "if" or "while".

I prefer to omit redundant braces for an "if" or "while" that controls a
single statement, but there is nothing terribly wrong about using them
every time. Some people say it reduces the likelihood of error, and
based on your experience maybe it does. I find it nicer to read the
code without them, but of course you have to understand the language
rules.
 
J

Jason

David Harmon said:
It is guaranteed to work the same on all compilers. This part of the
language syntax has been well defined from the very beginning of C, and
it would be a huge shock to find a compiler that got it wrong.

The thing controlled by an "if" or "while" is conceptually a single
statement. Multiple statements with braces around them are considered a
single "compound statement". If you want, you can put braces around a
group of statements that have nothing to do with any "if" or "while".

I prefer to omit redundant braces for an "if" or "while" that controls a
single statement, but there is nothing terribly wrong about using them
every time. Some people say it reduces the likelihood of error, and
based on your experience maybe it does. I find it nicer to read the
code without them, but of course you have to understand the language
rules.

Thanks for the reply(grr @ dig:)). I've never looked at the syntax rules
for a programming language I've used, I've just used it, but now I'm
interested, any online references to the complete syntax of c++ so I can
understand all the language rules? all i get on google is fricking adverts
for books.
 
J

Jack Klein

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.

Without showing us some of the code that behaved incorrectly, and what
you changed it to to make it behave the way you wanted it to, it is
difficult to say for sure what went wrong. Most likely you had an
"else" or "elseif" matched up to the wrong "if".

I have never seen a professional coding standard that did not require
the braces around all controlled clauses, even if they were only a
single statement. Nor will there ever be one anyplace I work where I
have any measure of control over the coding standard.

There is just too much chance for error, not only when writing the
original code, but even more so later when the code is modified for
defect fixing or upgrade.
 
G

Gianni Mariani

I have a policy of allways having a brace. In fact, if I had a compiler
option that would refuse anything but compound statements on
if/else/while etc I would hardwire it on. - simply because that one
behaviour if it eliminates one instance of an error I could make is
worth the price - I've seen that error happen with multiple people more
than I can count.
Thanks for the reply(grr @ dig:)). I've never looked at the syntax rules
for a programming language I've used, I've just used it, but now I'm
interested, any online references to the complete syntax of c++ so I can
understand all the language rules? all i get on google is fricking adverts
for books.

Occasionally it's good to buy books. Stroustrup's "The C++ Programming
Language" has a grammmer section which is an interesting reference.


Here's a google hit:

http://www.csci.csusb.edu/dick/c++std/cd2/gram.html
 
J

Jack Klein

Certainly requiring braces seems to have wide acceptance, but your
statement is an exaggeration. Glancing quickly through the standard,
the Dinkumware standard library which ships with VC7.1, and the Boost
source, I find numerous uses of 'if' without braces. Generally the
meaning of such code is immediately clear.

Just serach for 'if (' in the standard.

Jonathan

The examples in the C and C++ standards are not, nor are they intended
to be, examples of a particularly robust coding style. Investigate
the literature and find the number of defects associated with the
practice of omitting braces.
 
J

Jonathan Turkanis

Jack Klein said:
I have never seen a professional coding standard that did not require
the braces around all controlled clauses, even if they were only a
single statement. Nor will there ever be one anyplace I work where I
have any measure of control over the coding standard.

There is just too much chance for error, not only when writing the
original code, but even more so later when the code is modified for
defect fixing or upgrade.

Certainly requiring braces seems to have wide acceptance, but your
statement is an exaggeration. Glancing quickly through the standard,
the Dinkumware standard library which ships with VC7.1, and the Boost
source, I find numerous uses of 'if' without braces. Generally the
meaning of such code is immediately clear.

Just serach for 'if (' in the standard.

Jonathan
 
J

Jonathan Turkanis

Jack Klein said:
The examples in the C and C++ standards are not, nor are they intended
to be, examples of a particularly robust coding style. Investigate
the literature and find the number of defects associated with the
practice of omitting braces.

That's an interesting response. You seemed to claiming general
acceptance of the pratice of including braces everywhere. (Maybe I
misinterpretted you.) Notice that I did not disagree that this is a
wise practice. I simply offered some evidence that the practive is not
nearly as widespread as you implied, even in code from very reputable
sources.

Now you tell me to 'investigate the literature'. You're the one making
the argument -- it's your responsibility to provide evidence for your
position.

Of course, the examples from the standard are not intended to be
examples of robust coding style. But certainly they are not examples
of bad style (excpet for those flagged as errors).

Jonathan
 
J

Jason

">
Occasionally it's good to buy books. Stroustrup's "The C++ Programming
Language" has a grammmer section which is an interesting reference.
thanks for the tip, I wish I had bought that book recently in preference to
the C++ Standard Library by Josuttis, which I have hardly needed to use. I
guess i can read about iterators and templates when i feel like it, but I
dont find it very helpful as I only ever used vector, string and few stream
objects from the STL. The only reason I did not buy Stroustrup was because
I have experience of reading K & R for the c language and assumed it would
be similar in style ie a little bit on the formal side and rather dull. I
suppose I will buy it anyway at some point.

thanks again.
 
D

David Harmon

I have a policy of allways having a brace. In fact, if I had a compiler
option that would refuse anything but compound statements on
if/else/while etc I would hardwire it on.

I would expect that almost any "lint" type product would allow you to
check for that.
 
N

Nick Hounsome

Jason said:
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.

The main problem with not including braces that I come across is poorly
written
macros particularly debug ones or ones requiring a local variable

For example:
#define DEBUG(s) if( debug ) puts(s)

This works ok for

if( x > 3 ) DEBUG("too big");

But fails miserably the moment you add an else/else if clause:

if( x > 3 ) DEBUG("too big"); else { // this will only happen if x >3 &&
!debug }

I use the braces but if you don't be sure to use the do..while trick -

#define DEBUG(s) do { if(debug) puts(s); /* local vars ... whatever */}
while(false)

This allows you to use the macro almost exactly as a function returning void
and
a good compiler will probably impose no overhead (although it may warn you
which is
annoying).
 
L

lilburne

Jonathan said:
Certainly requiring braces seems to have wide acceptance, but your
statement is an exaggeration. Glancing quickly through the standard,
the Dinkumware standard library which ships with VC7.1, and the Boost
source, I find numerous uses of 'if' without braces. Generally the
meaning of such code is immediately clear.

Perhaps they don't have coding standards, or neglect them
from time to time. Our coding standard requires braces
around all control statements and even 'outlaws' single line
variants:

if (a < b) function();
for (int x = 0; x < y; ++x) function();

yet from time to time you'll find such examples in the
codebase even written by the originators of the standard.
They get to fix it.
 
J

Jonathan Turkanis

lilburne said:
Perhaps they don't have coding standards, or neglect them
from time to time. Our coding standard requires braces
around all control statements and even 'outlaws' single line
variants:

if (a < b) function();
for (int x = 0; x < y; ++x) function();

yet from time to time you'll find such examples in the
codebase even written by the originators of the standard.
They get to fix it.

Maybe this policy should be adopted universely. My only point was that
it hasn't been even by people familiar with the problems which have
been mentioned in this thread.

Boost doesn't have coding standards -- just some general guidelines.
Obviously the standard doesn't have coding standards. But I'd be
surprised to learn Dinkumware doesn't.

Jonathan
 
L

lilburne

Jonathan said:
Boost doesn't have coding standards -- just some general guidelines.
Obviously the standard doesn't have coding standards. But I'd be
surprised to learn Dinkumware doesn't.

Maybe they do, or maybe it depends on seniority of the
person writing the code, or maybe occasionally things get
missed, or maybe they didn't want people whining about
'bloat' in header files. You can't tell just by examining
the code.

There are consideration other than just readability.
Personally, like others that have responded to this thread,
I consider that using braces removes a class of bugs and is
helpful for maintainance. Also as with Jack Klein if I have
any control of a coding standard I'd be insisting on braces
around all control statements.
 
J

Jonathan Turkanis

lilburne said:
There are consideration other than just readability.
Personally, like others that have responded to this thread,
I consider that using braces removes a class of bugs and is
helpful for maintainance. Also as with Jack Klein if I have
any control of a coding standard I'd be insisting on braces
around all control statements.

I thought Jack Klein was saying, 'you'd better get used to using
braces, since their in (just about) every professional coding
standard', not 'I wish I could add the requirement to my company's
coding standards.'

I guess I'll repeat one last time: I'm not against requiring braces.

Jonathan
 
S

stelios xanthakis

lilburne said:
Maybe they do, or maybe it depends on seniority of the
person writing the code, or maybe occasionally things get
missed, or maybe they didn't want people whining about
'bloat' in header files. You can't tell just by examining
the code.

There are consideration other than just readability.
Personally, like others that have responded to this thread,
I consider that using braces removes a class of bugs and is
helpful for maintainance. Also as with Jack Klein if I have
any control of a coding standard I'd be insisting on braces
around all control statements.

Well, you can't argue: Bugs cost. Yes? We want to eliminate
the possibility of bugs. Yes? It is not impossible that a drunken
idiot will introduce a bug because of braces. No? So we make
braces required then. Yes? Can't argue unless insane.

But K&R didn't make braces obligatory. And this is a symbolic move!
Because:

[1] Orthogonal logic

statement:
expression
compound-statement
if-statement
....

compound-statement: {
statement
}

and a compound-statement IS a statement

[2]
They say that good indention is very important (and should
be enough to avoid the braces problem therefore)

[3]
One should generally be focused when programming.


So: avoid braces like hell unless your employer forces you to
use them.

everybody happy with that?
 
O

Old Wolf

The main problem with not including braces that I come across is poorly
written macros particularly debug ones or ones requiring a local variable

For example:
#define DEBUG(s) if( debug ) puts(s)

This works ok for

if( x > 3 ) DEBUG("too big");

But fails miserably the moment you add an else/else if clause

This bug should have been caught in two other places:
- you should not write a macro that can be misused like that
- the person who wrote "if (blah) MACRO()" should have been more awake

I would not want to impose braces on all my code in order to avoid
that situation.

In my years of braceless coding I have only had a couple of
unexpected if..else behaviours, and one situation that took an hour
to find. IMHO this is not enough reason to start crippling
my code with unnecessary braces. The gist of it was:

if (blah)
some_large_expression();
else
return some_other_large_expression(),

// debug();
printf("blah was true\n");

and the function would print "blah was true" when blah was false,
and return the wrong thing, and I was even more annoyed by the fact
that if I put in the debug line then the behaviour would all change
again. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top