• Create Account

We need 1 more developer from Canada and 12 more from Australia to help us complete a research survey.

Support our site by taking a quick sponsored survey and win a chance at a \$50 Amazon gift card. Click here to get started!

# Coding Style: Curly Braces

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.

73 replies to this topic

### #21Servant of the Lord  Crossbones+   -  Reputation: 27122

Like
0Likes
Like

Posted 16 April 2013 - 04:50 PM

Actually, though. I do have one 'odd' habit that would probably get me smacked by some people.

if(condition) {/*dostuff in one line*/}


I never use 'braceless' blocks.

That's actually considered good, not something that'll 'get you smacked'.

It's not something I follow myself, but it is a good habit. It's not all that odd or uncommon either.

Edited by Servant of the Lord, 16 April 2013 - 04:50 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #22L. Spiro  Crossbones+   -  Reputation: 21445

Like
3Likes
Like

Posted 16 April 2013 - 05:47 PM

I also never use non-braced blocks.  They only cause confusion and leave the potential for future problems, especially when adding debug code to print values or just later updating code to do more than a single statement of work.

I prefer to keep my opening braces on the same line.  It feels cleaner and it reduces the use of vertical real-estate.

I personally don’t understand the main reason people put them on their own lines, which is that they are easier to pair up with the closing brace.

When I am scanning up from a closing brace to its opening brace, I go by indentation level and nothing else, so it doesn’t matter if there is specifically an opening brace at the same level as the closing brace or if it is an if, while, for, function declaration, etc.

Scanning only based on indentation levels keeps things simple and it means that code where braces are on their own lines is just as easy to read for me as any other style.

It is a huge problem when trying to read code that has not been indented consistently, but we can all agree that is a no-no.  Regardless of your bracing style, proper indentation is necessary.

But in practice I use whichever style is necessary.

In my own works, it is necessary (by the law of satisfying one’s own taste) to keep them on the same lines as the if/while/etc.

At the office, the general style is to put them on their own lines.  They aren’t so picky on that but I do it just to keep the code as consistent as possible, because that matters much more than which brace style you use.

L. Spiro

### #23Khatharr  Crossbones+   -  Reputation: 4113

Like
0Likes
Like

Posted 16 April 2013 - 11:26 PM

Yeah. Indentation is the main thing. Anime-Planet changed the format of a table in their user-page anime listing and I spent an hour making a 5-minute fix to a greasemonkey script last night because the html is indented using what appears to be the shotgun whitespace method. Finally I just copied out the page source into SciTE and corrected the indentation and everything became clear....

Well...

As clear as JS DOM gets, anyway.

Edited by Khatharr, 16 April 2013 - 11:27 PM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #24Dynamite Andy  Members   -  Reputation: 119

Like
0Likes
Like

Posted 17 April 2013 - 06:36 AM

When it comes to curly braces... I used to do this...

if (x == 0)
// do something
else
// do something else


But during university I was taught that I should always use curly braces and I should always comment everything - my lecturer was pretty strict with coding styles and marked us on the style instead of the code itself. Since leaving my coding style has changed from above to..

// 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
}


Personally I now find this easier on the eyes and easier to read,

However i've found myself now starting to do this for functions

void ReturnX() { return x; }


### #25Paradigm Shifter  Crossbones+   -  Reputation: 5676

Like
2Likes
Like

Posted 17 April 2013 - 06:45 AM

Someone needs to spank your lecturer if they think that comments such as those are acceptable. That's as bad as

i++; // increment i

EDIT: Comments should describe the usage or intent of the code, not the syntax

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

### #26siri  Members   -  Reputation: 283

Like
2Likes
Like

Posted 17 April 2013 - 07:01 AM

// 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, 17 April 2013 - 07:04 AM.

### #27Shaquil  Members   -  Reputation: 816

Like
0Likes
Like

Posted 17 April 2013 - 07:19 AM

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, 17 April 2013 - 07:28 AM.

### #28Álvaro  Crossbones+   -  Reputation: 16573

Like
0Likes
Like

Posted 17 April 2013 - 07:19 AM

// 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, 17 April 2013 - 07:20 AM.

### #29BCullis  Crossbones+   -  Reputation: 1943

Like
0Likes
Like

Posted 17 April 2013 - 11:08 AM

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.
Hazard Pay :: FPS/RTS in SharpDX
DeviantArt :: Because right-brain needs love too

### #30Azaral  Members   -  Reputation: 467

Like
0Likes
Like

Posted 17 April 2013 - 04:20 PM

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, 17 April 2013 - 04:20 PM.

### #31Madhed  Crossbones+   -  Reputation: 3715

Like
0Likes
Like

Posted 17 April 2013 - 05:04 PM

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.

### #32slicer4ever  Crossbones+   -  Reputation: 5475

Like
1Likes
Like

Posted 17 April 2013 - 05:57 PM

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


Check out https://www.facebook.com/LiquidGames for some great games made by me on the Playstation Mobile market.

### #33Aliii  Members   -  Reputation: 1452

Like
0Likes
Like

Posted 17 April 2013 - 07:45 PM

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;

}

}

}

### #34TheChubu  Crossbones+   -  Reputation: 7027

Like
0Likes
Like

Posted 17 April 2013 - 07:51 PM

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, 17 April 2013 - 07:52 PM.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

### #35Khatharr  Crossbones+   -  Reputation: 4113

Like
0Likes
Like

Posted 17 April 2013 - 11:27 PM

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


void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #36willpowered  Members   -  Reputation: 534

Like
1Likes
Like

Posted 18 April 2013 - 01:36 AM

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?

### #37Felix Ungman  Members   -  Reputation: 1290

Like
0Likes
Like

Posted 18 April 2013 - 01:58 AM

(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, 18 April 2013 - 01:59 AM.

openwar  - the real-time tactical war-game platform

### #380r0d  Members   -  Reputation: 831

Like
0Likes
Like

Posted 18 April 2013 - 02:31 AM

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.

### #39Khatharr  Crossbones+   -  Reputation: 4113

Like
-1Likes
Like

Posted 18 April 2013 - 03:13 AM

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

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #40L. Spiro  Crossbones+   -  Reputation: 21445

Like
0Likes
Like

Posted 18 April 2013 - 04:00 AM

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

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