Followers 0

# Coding Style: Curly Braces

## 73 posts in this topic

// Used to check if x is equal to 0
if (x == 0)
{
x  =  5;        // give x the value of 5
}
else                 // if x is not equal to 0 then do this
{
x = 4;         // give x the value of 4
}

Did he mark you down for not commenting the curly braces themselves ?

Pretty much every comment there is unnecessary in my opinion. There is such a thing as commenting too much and hindering readability.

As for me I tend to use braces in this manner:

void func() {
}


I'm not sure why it's just habit. I've recently started using C# and found the auto-formatting in VS very annoying. Took me a while to work out how to disable it.

Edit:

Just occurred to me that the block Andy posted was likely just an example.

Edited by siri
2

##### Share on other sites

in-fact i wouldn't mind if C++ ditched the braces completely in the next version of the standard and switched to using indentation to set the scope)

Easy there, trigger.

EDIT:

By the way, I've never asked anyone this because I've rarely had anyone else read my code, but I wonder if this habit I have is a case of "overcommenting." Basically, I keep the opening brace on the same line, and I always comment the closing brace, even if it's really really obvious. It helps me with re-reading my code, but I do sometimes wonder if another programmer might think I'm overdoing it haha. For example:

void myFunction(){
if(/*condition*/){
doSomething(x, y);
doSomethingElse(a, b);
switch(/*condition*/){
case blah:
break;
}//end of switch
}//end of if
}//end of myFunction()

Edited by Shaquil
0

##### Share on other sites

// Used to check if x is equal to 0
if (x == 0)
{
x  =  5;        // give x the value of 5
}
else                 // if x is not equal to 0 then do this
{
x = 4;         // give x the value of 4
}


The only comment I want in that code is one explaining what x' means, and why it makes sense that up to that point in the code values like 0 or something else made sense, and after that point in the code 4 and 5 make sense. Separating x into two variables (one for whatever it represented up to that point in the code and one for whatever it represented after that point in the code) and giving them good names would result in code that is much more readable than that horrible thing you just posted.
int default_number_of_tax_allowances = (number_of_children == 0) ? 5 : 4;

Edited by Álvaro
0

##### Share on other sites

EDIT:

By the way, I've never asked anyone this because I've rarely had anyone else read my code, but I wonder if this habit I have is a case of "overcommenting." Basically, I keep the opening brace on the same line, and I always comment the closing brace, even if it's really really obvious. It helps me with re-reading my code, but I do sometimes wonder if another programmer might think I'm overdoing it haha. For example:

void myFunction(){  if(/*condition*/){    doSomething(x, y);    doSomethingElse(a, b);    switch(/*condition*/){       case blah:           break;    }//end of switch  }//end of if}//end of myFunction()

I actually started doing that recently because it really helps clear up the end of a 4- or 5-level nested loop if you want to add to it later. After using lisp in college, I made a habit of always writing my opening and closing brace/parens IMMEDIATELY, and then adding the content inside. This leads to chains of closing braces at the end of some of my more workhorse functions or complex algorithms and it's really nice to have the tags via comments to see where you want to jump in to do something "inside loop 2 but post switch case".

Also, in general to the thread, I ALWAYS brace my conditionals, even if they're on one line. I've had too many stealth bugs creep in because I had skipped braces on a one-line if statement and added a second instruction.
0

##### Share on other sites

EDIT:

By the way, I've never asked anyone this because I've rarely had anyone else read my code, but I wonder if this habit I have is a case of "overcommenting." Basically, I keep the opening brace on the same line, and I always comment the closing brace, even if it's really really obvious. It helps me with re-reading my code, but I do sometimes wonder if another programmer might think I'm overdoing it haha. For example:

void myFunction(){  if(/*condition*/){    doSomething(x, y);    doSomethingElse(a, b);    switch(/*condition*/){       case blah:           break;    }//end of switch  }//end of if}//end of myFunction()

I actually started doing that recently because it really helps clear up the end of a 4- or 5-level nested loop if you want to add to it later. After using lisp in college, I made a habit of always writing my opening and closing brace/parens IMMEDIATELY, and then adding the content inside. This leads to chains of closing braces at the end of some of my more workhorse functions or complex algorithms and it's really nice to have the tags via comments to see where you want to jump in to do something "inside loop 2 but post switch case".

Also, in general to the thread, I ALWAYS brace my conditionals, even if they're on one line. I've had too many stealth bugs creep in because I had skipped braces on a one-line if statement and added a second instruction.

I too automatically create the open and closed braces for bodies of code and then go back in and put the code in the body.

I don't think putting a comment at the end of braces is a bad idea at all, especially if you have a lot of nesting and things going on. Whatever helps you and others understand your code easier is not a waste of time in my opinion as long as you don't over do it.

Edited by Azaral
0

##### Share on other sites

I use K&R style.

With one exception:

This is super ugly:

if (foo) {
bar();
} else {
baz();
}


Wile this is great:

if (foo) {
bar();
}
else {
baz();
}


I think it's called CCR style. Compact control readability.

0

##### Share on other sites

I use K&R style.
With one exception:

This is super ugly:

if (foo) {
bar();
} else {
baz();
}

Wile this is great:
if (foo) {
bar();
}
else {
baz();
}

I think it's called CCR style. Compact control readability.

honestly, for something like that, I think both are ugly, and would prefer the compact:
if(foo) bar();
else    bar();

1

##### Share on other sites

I use the latter one, ...however the first one is more readable for everyone in general. IMO

Plus I add a few conventions. Like if I put a linebreak when there is more than 1 statement after the cycle-s or if-s.

for( something){

while( something){

if( something){

statemet1;

statemet2;

statemet3;

}

}

}

0

##### Share on other sites

I always look at control blocks with one line, no braces and think "Someday I'm going to mess this up" So I always put braces even if the if/else block can fit in a single line.

Something I took from Id Software coding style manual is the spacing between parenthesis, ie:

if ( this.vertexBuffer == null )

if ( enable )

if ( this.dirty )

And so on. Its more pleasing to the (my) eye.

Sometimes, if the conditions are many I treat the parenthesis as if it were another curly braces block like this:

mode = modeArray[i];
if
(
mode.getWidth() == width &&
mode.getHeight() == height &&
mode.getFrequency() == 60 &&
mode.getBitsPerPixel() == 32
)
{
Display.setDisplayMode(mode);
break;
}

This one I haven't seen it elsewhere yet.
Edited by TheChubu
0

##### Share on other sites

I'll do that occasionally. More often, though, I'll just put the condition into a bool and then run the bool through the if statement.

mode = modeArray[i];

bool resetDisp =
(mode.getWidth() == width) &&
(mode.getHeight() == height) &&
(mode.getFrequency() == 60) &&
(mode.getBitsPerPixel() == 32);

if(resetDisp) {
Display.setDisplayMode(mode);
break;
}

0

##### Share on other sites
bool f1() {
//...
}

bool f2() {
//...
}

bool f3() {
//...
}

if(f1()) {
if(f2()) {
if(f3()) {
//...
}
}
}


To me, this is the clearest way. Why waste a line, when it's clear that if you have proper indentation, the close bracket will always align with the statement that opens it?

1

##### Share on other sites

(we all want to read code that looks exactly like our style I'm sure).

Well, my approach is something like this:

1 - practice reading code in a lot of different styles and get comfortable with doing it

2 - practice *writing* code in a lot of different sales and get comfortable with doing it

3 - get to know and use the formatting tools of your IDE

4 - be consistent and follow style of the code that you are working with

Consistency is far more important that the particular style.

What style do you tend to use and like better?  What are you reasons you chose that specific style for curly braces?

The primary formatting tool is whitespace, and I personally prefer lots of whitespace and large monitors to compact code so curlys usually get the line to themselves.

Edited by Felix Ungman
0

##### Share on other sites

f(f1()) {
if(f2()) {
if(f3()) {
//...
}
}
}


To me, this is the clearest way. Why waste a line, when it's clear that if you have proper indentation, the close bracket will always align with the statement that opens it?

The reason this style is bad is because it's inconsistent and doesnt align the matching braces.  The opening brace is at the end of the first line of the code block, while the closing grace is inexplicably on its own line after the code block.  No consistency whatsoever.  Since you're aligning the end-brace with code instead of an open-brace, that open brace might not even be there and you'd never notice until the compile fails, which might be a significant amount of time wasted on big projects.

It's not even consistent with what you claim to be the reason for using it... namely because you dont want to "waste a line".  I'm not sure why you think that packing your code together as much as possible is desirable (it's not), but if that's the case then why put the closing brace on a separate line?  Why is "wasting" that line acceptable?  By your logic, this is the code you should be writing:

if(f1()) {
if(f2()) {
if(f3()) {
/*...*/ } } }


No "wasted" lines there, and the brace placement is consistent... always at the end of the first/last line.  And, of course if you really dont want to waste lines, then this is what you should be doing:

if(f1()) { if(f2()) { if(f3()) { /*...*/ } } }


There you go, I just saved you 86% of the lines in that code block and made the brace placement perfectly consistent.  You dont have to thank me.

Now, for those of us that dont want to pack code into an indecipherable brick, having braces on their own lines gives a natural break to separate sections of code for better readability, and has the advantage that braces are always aligned with each other, making the pattern easy to spot from a mile away.  For example:

void Character::SaveState(FILE *pFile){
fwrite(&mHealth, 1, sizeof(mHealth), pFile);
fwrite(&mMoney, 1, sizeof(mMoney), pFile);
fwrite(&mPosition, 1, sizeof(mPosition), pFile);
fwrite(&mWeapon, 1, sizeof(mWeapon), pFile);
}

as opposed to:

void Character::SaveState(FILE *pFile)
{
fwrite(&mHealth, 1, sizeof(mHealth), pFile);
fwrite(&mMoney, 1, sizeof(mMoney), pFile);
fwrite(&mPosition, 1, sizeof(mPosition), pFile);
fwrite(&mWeapon, 1, sizeof(mWeapon), pFile);
}


A cursory look through the second set of code easily distinguishes the function declaration from the code in the body, making both easier to read.  Even better would be:

void Character::SaveState(FILE *pFile)
{
fwrite(&mHealth,   1, sizeof(mHealth),	 pFile);
fwrite(&mMoney,	   1, sizeof(mMoney),	 pFile);
fwrite(&mPosition, 1, sizeof(mPosition), pFile);
fwrite(&mWeapon,   1, sizeof(mWeapon),	 pFile);
}


Here your brain can use its full pattern-matching abilities to easily spot discrepancies as quickly as possible.  Finding bugs in code like this becomes extremely easy because you're not fighting your brain and intentionally obfuscating the code, you're actually using the code formatting to help in finding errors.

0

##### Share on other sites

-snip-

The reason this style is bad is because it's inconsistent and doesnt align the matching braces.  The opening brace is at the end of the first line of the code block, while the closing grace is inexplicably on its own line after the code block.  No consistency whatsoever.  Since you're aligning the end-brace with code instead of an open-brace, that open brace might not even be there and you'd never notice until the compile fails, which might be a significant amount of time wasted on big projects.

It's not bad. It's just not the style you use. The end brace matches the block owning statement. It reads very naturally to people who prefer that style.

-1

##### Share on other sites

f(f1()) {
if(f2()) {
if(f3()) {
//...
}
}
}


To me, this is the clearest way. Why waste a line, when it's clear that if you have proper indentation, the close bracket will always align with the statement that opens it?

The reason this style is bad is because it's inconsistent […] The opening brace is at the end of the first line of the code block, while the closing grace is inexplicably on its own line after the code block.  No consistency whatsoever.

Consistency has to do with picking one style and sticking to it throughout the code base. It has nothing to do with braces being on the same indentation level.

The reason this style is bad is because [it] doesnt align the matching braces.

How is that bad? People tend to scan 90% by indentation levels, and since bad indentation will screw up anyone in either style it is always necessary for indentation to be consistent.
So, when combined with the following quote of yours:

Now, for those of us that dont want to pack code into an indecipherable brick, having braces on their own lines gives a natural break to separate sections of code for better readability, and has the advantage that braces are always aligned with each other, making the pattern easy to spot from a mile away.

…the other side could question why you get so tripped up over such a small detail. Training yourself to spot specifically the opening brace rather than just anything on the same indentation level seems counter-intuitive and self-limiting. After all, you wouldn’t spot the opening brace unless it was on the same indentation level as the closing brace, so you wouldn’t spot that any faster than the other side would spot the if, else, while, for, etc. In fact it takes you more effort and time since you are apparently looking for one specific character, when the other side is looking for anything on the same indentation level. Once the other side finds anything on the same indentation level, they immediately say, “Ah, found it,” whereas you say, “Ah, okay is it an opening brace? Okay found it.”

The other side might then say that if you claim to spot things just as quickly as they do, then you aren’t truly looking for specifically an opening brace; you are going entirely by indentation level, since it is matter-of-fact that checking for specific characters is an extra step that can’t be done in the same amount of time by the same processor.
So then the other side would question why the brace needs to use an extra line on its own if it is not actually helping you align things with closing braces. Then it becomes quite obvious that you can’t actually say it has any justifiable purpose, but rather just that you prefer it to be on the same level as the closing brace, as a matter of your own personal taste and nothing more.

This gives the other side a legitimate claim to it being a waste of space. By their logic, it serves nothing more than to placate your personal taste, but with the downside of moving a few lines of code off the bottom of the screen. That doesn’t mean they want the code as compact as possible, but that they prefer to choose where to compact it or where to not.

For example:

	LSUINT32 LSE_CALL CTime::GetConstantStepUpdateTimesFromTicks( LSUINT64 _ui64Ticks, LSUINT32 &_ui32UnitsToNextUpdate ) {
LSUINT64 ui64TimeNow = GetRealTime();
LSUINT64 ui64Dif = ui64TimeNow - m_ui64LastRealTime;

LSUINT32 ui32Count = static_cast<LSUINT32>(ui64Dif / _ui64Ticks);
m_ui64LastRealTime += ui32Count * _ui64Ticks;

// Determine how far this update lands between two other updates at the same fixed interval,
//	in units of 1 1,000th.
_ui32UnitsToNextUpdate = static_cast<LSUINT32>(((ui64Dif % _ui64Ticks) * 1000ULL) / _ui64Ticks);

return ui32Count;
}

Blank lines were added to make logical separations between segments of code, and a 2-line comment added for clarity on the return.
The other side won’t see a purpose in adding an extra line after the function declaration just for the brace because it doesn’t improve readability in any way—blank lines were added in strategic places rather than religiously at the start of the function, and it is very clear where the function body begins based on indentation levels alone.

I am offended that you use a style other than my own so let me twist your logic and write a totally out-of-context example:

if(f1()) {
if(f2()) {
if(f3()) {
/*...*/ } } }


Let me try to offend you even more by throwing all logic out the window and pretend the concept of indentation levels just doesn’t exist, even though I use them myself when scanning for matching braces:
if(f1()) { if(f2()) { if(f3()) { /*...*/ } } }


Careful, someone might misunderstand that you are close-minded and stuck in your own ways, justifying them as “the best” based solely on the fact that it is what you prefer.

Of course, we all know better than that, right?

L. Spiro

0

##### Share on other sites

It seems to me that the main reason being put forward for preferring K&R (or similar) is saving space, but don't you think that this is a case of seriously getting things entirely the wrong way around?  The purpose of a coding style is not to save space or to look pretty, it's to make code easier to read (because reading code is harder than writing code), to make wrong code look wrong and to make right code look right.

If we can all agree, or mostly agree, that a certain style is harder to read or fails in the other main criteria, then we should by definition also all agree (or mostly agree) that any other advantages that style may have are of reduced (or no) importance.  If a given style takes 50% longer for a person to read and parse then that's time wasted for that person (and why obsess over saving a few blank lines if it comes at the cost of wasting someone's time?)  If a given style makes right code look wrong (or worse - wrong code look right) then that style is obviously at best flawed, at worst completely broken.

0

##### Share on other sites

It seems to me that the main reason being put forward for preferring K&R (or similar) is saving space, but don't you think that this is a case of seriously getting things entirely the wrong way around?  The purpose of a coding style is not to save space or to look pretty, it's to make code easier to read (because reading code is harder than writing code), to make wrong code look wrong and to make right code look right.

See my previous example.

	LSUINT32 LSE_CALL CTime::GetConstantStepUpdateTimesFromTicks( LSUINT64 _ui64Ticks, LSUINT32 &_ui32UnitsToNextUpdate ) {
LSUINT64 ui64TimeNow = GetRealTime();
LSUINT64 ui64Dif = ui64TimeNow - m_ui64LastRealTime;

LSUINT32 ui32Count = static_cast<LSUINT32>(ui64Dif / _ui64Ticks);
m_ui64LastRealTime += ui32Count * _ui64Ticks;

// Determine how far this update lands between two other updates at the same fixed interval,
//	in units of 1 1,000th.
_ui32UnitsToNextUpdate = static_cast<LSUINT32>(((ui64Dif % _ui64Ticks) * 1000ULL) / _ui64Ticks);

return ui32Count;
}

If it were easier to read to put a blank line I would put one there. While keeping the brace on the same line as the function declaration.
It isn’t truly about saving space; that is just a simplification. It’s about deciding where blank lines go based on actual considerations for the code at hand rather than just following a “rule” (note that it is not meant to be such a rule but many make it out as such just as many over-simplify K&R as aiming to save space) which may or may not be appropriate for any given code block.

Again, strategically placed blank lines certainly do improve readability, but there is no rule or even a remote human consensus that blank (or lines containing only opening braces) improve readability in all cases after function headers, if’s, else’s, while’s, for’s, etc.

I personally believe that a blank line after a namespace declaration is universally easier to read.
So I put a blank line there. You could instead choose to put an opening brace on its own line there, but that is nothing but personal preference.

L. Spiro
0

##### Share on other sites

On the other hand, you've got this:

if ((a || b) && (c || d) && (e || f)) {
DoSomething ();
DoSomethingElse ();
}


Versus this:

if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}


The second one here is wrong (and won't even compile, but that's by the by for now) but the wrongness doesn't jump out at you like it should.

0

##### Share on other sites

if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}


The second one here is wrong (and won't even compile, but that's by the by for now) but the wrongness doesn't jump out at you like it should.

It does jump on you immediately when the editor automatically indents the code.

    if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}

0

##### Share on other sites

On the other hand, you've got this:

if ((a || b) && (c || d) && (e || f)) {
DoSomething ();
DoSomethingElse ();
}


Versus this:

if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}


The second one here is wrong (and won't even compile, but that's by the by for now) but the wrongness doesn't jump out at you like it should.

What would be even worse is if you have an open bracket somewhere before that and you are missing ITS' closing bracket. That errant closing bracket for that if statement would then take the place of the missing closing bracket for the previous one. Probably not terribly likely to happen, but if it did I bet it would be a pain to find.

0

##### Share on other sites

On the other hand, you've got this:

if ((a || b) && (c || d) && (e || f)) {
DoSomething ();
DoSomethingElse ();
}


Versus this:

if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}


The second one here is wrong (and won't even compile, but that's by the by for now) but the wrongness doesn't jump out at you like it should.

Basically, both sides can point out rare edge cases, which is why the debate never ends.

Every style has edge cases. You get around them by coding right.
For example, C++ makes it easy to leak memory. To “code right” I either added the new and then immediately add the delete when I was young, or use RAII as I grew more experienced.
Likewise, I never miss braces because both the opening and closing brace are added together, before the body of the block is added.
I can see fairly easily then if I missed something. Such a mistake is actually glaringly obvious, and similar edge cases exist in all styles.

It’s really not related to formatting any more than writing a delete for every new as a pair is. Safe coding practices prevent this type of issue 99.9% of the time (and I can personally say I have never fallen prey to the example you provided; the only time in any style I have ever gotten mismatched braces was during refactors of heavily nested code, and while they were nasty, they would have popped up regardless of the style I chose).

L. Spiro
0

##### Share on other sites

On the other hand, you've got this:

if ((a || b) && (c || d) && (e || f)) {
DoSomething ();
DoSomethingElse ();
}


Versus this:

if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}


The second one here is wrong (and won't even compile, but that's by the by for now) but the wrongness doesn't jump out at you like it should.

I've programmed in that style for a long time, it jumped out to me immediately, without any need for an editor to format it and before reading your last sentence pointing it out.  I understand the point you are trying to make, but having coded like that for a long time, such mistakes very rarity occur, and when they do, i'm not digging through a ton of code to find it, it's generally pretty quick and easy to discover.

Edited by slicer4ever
0

##### Share on other sites

It's obviously personal preference, but I very much prefer the first type (and leave away braces for single line statements... when I'm feeling evil that might include using a comma operator) because I find it much more readable and despise the javaesque second style.

Addendum: If speed doesn't matter, I'll much rather choose the python no-braces style (tabs only for indents!), though this practically enforces the second brace style for implicit line continuations due to parentheses, braces and brackets.

Edited by l0calh05t
0

##### Share on other sites

Both coding styles are fine and I would be fine using either. The only style I cannot stand is the GNU style of having half-indented braces. Very annoying to maintain, and if a real TAB slips through the code it's going to look real ugly with different tab settings.

Coding style is a programmer's signature. If you get to call the coding style to be used (or if it's your own personal project) pick a style you like and stick with it, consistency is more important here.

That being said, personally, I have a preference for putting my opening braces on their own line because it makes the blocks pop out more. I already put a lot of white lines in my code to separate the logical "sub-tasks" of a function, and a condition block of a few lines is definitely a sub-task that I would white-line anyway, so putting the brace on its own line feels more consistent and natural with my coding style.

It also serves to separate the condition from the blocks. For short conditions this is a non-issue, but for long conditions that span on multiple lines it becomes harder to quickly spot where the condition begins without that empty white line.

1

##### Share on other sites

if ((a || b) && (c || d) && (e || f))
DoSomething ();
DoSomethingElse ();
}


The second one here is wrong (and won't even compile, but that's by the by for now) but the wrongness doesn't jump out at you like it should.

Then again, you can make the same example like this:

if ((a || b) && (c || d) && (e || f));
{
DoSomething();
DoSomethingElse();
}`

And this will not even generate a compiler error, maybe a warning. Truth is I don't think a bracket style will prevent human errors in the code, as no matter where you place them, a single mistyped character can break them.

Personally I prefer to use indention over brackets to see the structure of a code, it's must faster to scan code by indention level then by looking for the tiny brackets. Also modern IDEs are more then capable of visualizing scopes for you, for example in QtCreator:

0

## Create an account

Register a new account

Followers 0

• 12
• 28
• 14
• 11
• 34