• Create Account

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

Posted 15 April 2013 - 02:10 PM

I guess this is just a question out of interest in what people prefer to read and/or write code (we all want to read code that looks exactly like our style I'm sure).

Curly Braces.  When do you use them?  I know a lot of our personal coding styles can come from the places you learned from then we develop our own style later on.  Maybe the curly braces is just something people use a certain way because it's how they were always taught so they always saw code that way.

I myself always tend to do the following:

void SomeFunction(int x)
{
if( x > 10)
{
// Do something
}
}



Though I do a lot of times see the style of:

void SomeFunction(int x) {
if( x > 10) {
// Do something
}
}



I myself always seem to have "trouble" reading that if their is a lot going on.  I'm sure it is mostly because I am still learning of course and developing my own styles that I am just not used to reading it like that.

I tend to use the first one because for me it helps me see and visualize the scope a lot better.  I feel just by taking a quick glance at it I can tell you which scope I am in and have no problem.

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

### #2matrisking  Members

Posted 15 April 2013 - 02:16 PM

POPULAR

I prefer the first one as well.  Like you said, I think it's much easier to quickly visualize how blocks are nested.  I tend to use curly braces even for one line blocks just because I find it easier to read.  The biggest counter-argument I've heard is that you can fit more lines of code on your screen using the latter.

However, as you seem to be aware, it's a highly subjective topic that will cause a flame war as often as not.  Here's the most "objective" answer you're going to get:

If you're programming by yourself, use whatever is easiest for you to read.

If you're creating something new that involves other people, agree on a set of standards when you're planning the project and stick to them.

If you're working with an existing code base, adapt to the existing code standards for that project.

### #3Álvaro  Members

Posted 15 April 2013 - 02:18 PM

If you are working with other people in a project, do what they do. That's really the only rule we follow in my company, and over time we have developed a pretty uniform style of code formatting, without ever having to argue over any of this.

In the specific case of curly braces, we use the latter style, which I prefer because I value vertical real estate in programming. But either one is fine.

### #4Cornstalks  Members

Posted 15 April 2013 - 02:18 PM

If I have code on multiple lines, I always use braces. But if the code can comfortably fit on one line, then I use no braces (and only one line). For example:
// The following comfortably fits in one line, so I put it on one line with no braces:
if (x < 0) x = 0;
else if (x > 100) x = 100;

// The following doesn't comfortably fit on one line, so it goes on multiple lines with braces:
if (someObject.getPosition().x < 0)
{
someObject.setPosition(0, someObject.getPosition().y);
}
else if (someObject.getPosition().x > 100)
{
someObject.setPosition(100, someObject.getPosition().y);
}

I also put braces on their own line.

But I don't get too religious about it, and if I'm working on a project that uses a different convention I'm fine doing it (like K&R style). I like the vertical real estate that putting braces on the same line as the code saves, but I also like the spacing/formatting that putting braces on their on line gives, which is why I think I can easily switch between styles depending on the conventions of each project. I've learned to find the positives in various styles, and if I'm working on a project where I can't set the coding conventions, I focus on the positives of the chosen style which has helped me get over the religiosity of braces.

Edited by Cornstalks, 15 April 2013 - 02:23 PM.

[ 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 ]

### #5stitchs  Members

Posted 15 April 2013 - 02:29 PM

The first style is my personal preference aswell. And for the reason you mentioned, it makes everything a bit clearer, adds that extra spacing between lines, and allows quick identification of which braces are paired, and where nesting occurs.

I did dabble in the second type, when I thought less lines = the way to go! But after a while it became a slight headache. Again, it's personal preference to the coder and one persons style may not suit another. But, think about people reading it later, I want them to be able to read it as clearly and concisely as possible.

There is also the usage of no braces being used. This occurs if an 'if' statement is only intended to trigger 1 function.

if(someClauseIsTrue)
fireThisFunction();

I also used to do this, but again, it becomes a bit of a headache when you quickly skim it.

Regards,

Stitchs.

Edited by stitchs, 15 April 2013 - 02:29 PM.

### #6SimonForsman  Members

Posted 15 April 2013 - 02:41 PM

personally i prefer the second approach, i don't really see the point in putting the initial brace on its own line when the indentation makes everything clear anyway. (Python does just fine without any braces at all, 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)

Edited by SimonForsman, 15 April 2013 - 02:43 PM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

### #7Servant of the Lord  Members

Posted 15 April 2013 - 02:42 PM

My method is similar to the one CornStalks mentioned, with minor differences.

For simple single-line statements, I'd go without brackets:
if(...) //simple single-line statement
if(...) //simple single-line statement
But if they are chained ('else-if' or 'else'), I make the entire chain use brackets:
if(...)
{
//...more complex statements....
}
else if(...)
{
//...more complex statements....
}
If an 'if' is stand-alone, but is multi-lined, or even single-lined but cluttered, I'll fully brace it.
Or, even if the statement itself is simple, but the conditional is more complex, I'd brace it.
if(x == foo && y == (N - 7)
|| z == PI)
{
//Fully braced, because of non-simple conditional.
}

Edited by Servant of the Lord, 15 April 2013 - 02:47 PM.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' 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 -

### #8EddieV223  Members

Posted 15 April 2013 - 02:44 PM

I used to code like this

void MyFunc()

{

int x = 2;

}

But then I read a book called Code Complete 2nd ed.  And it gave a great explaination why that style is bad and the other 2 styles that are good.  So now I code like this

void MyFunc()

{

int x = 2;

}

This style really pays off in complex nested loops and if statements, because you look straight down the braces and everything at that tab depth belongs to the line above, no question about it.  The first style breaks down and gets very confusing within complex code.

The other style the book said was good was

void MyFunc() {

int myInt = 2;

}

After comparing the 2 the straight line block of the 1st suggested method is much easier to read.  And thats what it is really about, making sure that your blocks are clearly defined so your brain can easily figure out the scopes and owner of blocks.

Edited by EddieV223, 15 April 2013 - 02:46 PM.

If this post or signature was helpful and/or constructive please give rep.

// C++ Video tutorials

// Easy to learn 2D Game Library c++

SFML2.2 Tutorials http://www.sfml-dev.org/tutorials/2.2/

// Excellent 2d physics library Box2D

// SFML 2 book

Posted 15 April 2013 - 02:49 PM

If I have code on multiple lines, I always use braces. But if the code can comfortably fit on one line, then I use no braces (and only one line). For example:

// The following comfortably fits in one line, so I put it on one line with no braces:
if (x < 0) x = 0;
else if (x > 100) x = 100;

// The following doesn't comfortably fit on one line, so it goes on multiple lines with braces:
if (someObject.getPosition().x < 0)
{
someObject.setPosition(0, someObject.getPosition().y);
}
else if (someObject.getPosition().x > 100)
{
someObject.setPosition(100, someObject.getPosition().y);
}

I also put braces on their own line.

But I don't get too religious about it, and if I'm working on a project that uses a different convention I'm fine doing it (like K&R style). I like the vertical real estate that putting braces on the same line as the code saves, but I also like the spacing/formatting that putting braces on their on line gives, which is why I think I can easily switch between styles depending on the conventions of each project. I've learned to find the positives in various styles, and if I'm working on a project where I can't set the coding conventions, I focus on the positives of the chosen style which has helped me get over the religiosity of braces.

I have noticed I too seem to use only one line if it can easily fit on one line and be easily read.

Thanks for the reply everyone.  I know I just need to use what I like for personal projects find a consistent convention when working with teams.  Just interested what people used for their convention for curly braces since I see a lot of different styles for them.  Not meaning to start flame war.

### #10Servant of the Lord  Members

Posted 15 April 2013 - 02:50 PM

@EddieV223:

Either my humor-detector broke again (very likely!), or you misread the book.

Code Complete 2nd Edition says your first method is the good one, and the other two are bad, and explains why.

*pulls down the book to double-check*

Huh, I'm mistaken - It does seem to say that (page 742).

I'll have to reread the book soon - it's been several years.

Edited by Servant of the Lord, 15 April 2013 - 02:56 PM.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' 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 -

### #11NightCreature83  Members

Posted 15 April 2013 - 03:29 PM

My method is similar to the one CornStalks mentioned, with minor differences.

For simple single-line statements, I'd go without brackets:

if(...) //simple single-line statement
if(...) //simple single-line statement
But if they are chained ('else-if' or 'else'), I make the entire chain use brackets:
if(...)
{
//...more complex statements....
}
else if(...)
{
//...more complex statements....
}
If an 'if' is stand-alone, but is multi-lined, or even single-lined but cluttered, I'll fully brace it.
Or, even if the statement itself is simple, but the conditional is more complex, I'd brace it.
if(x == foo && y == (N - 7)
|| z == PI)
{
//Fully braced, because of non-simple conditional.
}

I'd say always use brackets and on new lines, you never know when you want to extend an if or else clause in the future with additional code. If it is a simple statement use a ternary operator for it, if you really wanna keep it on one line.

Btw here is the insomniac coding guide line and this is or something very similar (mostly comes down to camel casing on members and local variable declarations that's different) is used in a few places: http://www.insomniacgames.com/core-coding-standard/

Edited by NightCreature83, 15 April 2013 - 03:29 PM.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max

### #12mhagain  Members

Posted 15 April 2013 - 04:01 PM

I personally find the second style incredibly difficult to read at more than 1 indentation level because when identifying blocks of code I visually match the opening and closing brace; having them lined up in the same column is essential to me.

I value that over vertical real-estate any day; plus with Visual Studio you can auto-hide all the little pop-up panels anyway, which - when coupled with the fact that larger monitors are quite cheap these days - somewhat lessens the arguments in favour of the second.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.

### #13Amr0  Members

Posted 15 April 2013 - 04:23 PM

if( sOpinionQuery == "curly_braces_style_preference" )
{
gamedev.curThread.value += 0.02; // my two cents.
gamedev.desiredFeatures += "forum polls";
}
else
OneLiner();


### #14Musikai  Members

Posted 15 April 2013 - 04:37 PM

I personally find inline braces really hard to read when there's more than a few lines of code. I'ts much easier to identify code blocks when the braces match virtically.

Edited by Musikai, 15 April 2013 - 04:38 PM.

### #15Azaral  Members

Posted 15 April 2013 - 07:56 PM

The first style is much easier to read. I use curly braces anytime there is a block of code inside of something. I find the second way VERY difficult to read. The curly braces inline with the thing they are forming the body of, and everything inside that body is indented.

if( a == b )
{
if( a == c )
{
if( a == d )
{
do stuff
}
}
}


### #160r0d  Members

Posted 15 April 2013 - 08:02 PM

guess this is just a question out of interest in what people prefer to read and/or write code (we all want to read code that looks exactly like our style I'm sure).

Curly Braces.  When do you use them?  I know a lot of our personal coding styles can come from the places you learned from then we develop our own style later on.  Maybe the curly braces is just something people use a certain way because it's how they were always taught so they always saw code that way.

I myself always tend to do the following:

void SomeFunction(int x)
{
if(x > 10)
{
// Do something
}
}



This style is the best one.  The reasons are that it's self-consistent and aligns the braces with each other.  If you're missing a brace it's easy to scroll down and see where it's missing.  The human brain is great at pattern matching.  Anything that helps the brain do its thing will help your productivity.  Aligning and matching things that go together helps this.

This applies to braces, but also to any code formatting and alignment.  Group similar things together and without even trying your brain will spot whatever is out of place... which many times will be a bug.

Another example:

void SomeFunction(int x)
{
if	(x > 40) { /* ... */ }
else if	(x > 30) { /* ... */ }
else if	(x > 20) { /* ... */ }
else if	(x > 10) { /* ... */ }
else		 { /* ... */ }
}


### #17kidman171  Members

Posted 16 April 2013 - 05:49 AM

What about using the best of both worlds?

int  doSomething(int x)
{     int y;
// ... do complex operation
return y;
}



### #18japro  Members

Posted 16 April 2013 - 06:40 AM

Using the first style makes you a better coder since less code fits on the screen so you have to write more concise code and break functions into pieces earler

(I prefer the first style mainly out of habit but always adapt to existing codebases)

### #19Bacterius  Members

Posted 16 April 2013 - 07:14 AM

What about using the best of both worlds?

int  doSomething(int x)
{     int y;
// ... do complex operation
return y;
}



This can be tedious to format if you don't have smart tabbing functionality (though I agree this is a weak argument). But it just looks so wroooooooooooong...

Personally I've always used the first style because it is much more consistent to me, and clearly delimits scopes. Sure, it might take up a few more lines of code, but the curly braces are neatly on the same indentation level, rather than having one of the curly braces placed at the end of an arbitrarily long statement.

I also like the Python way - do away with curly braces altogether - though it brings its own set of issues (is this a tab or a space?)

This is kind of a subjective opinion, though, and it's best to go with what is already being used in the codebase since having two or more different coding styles competing with each other can be very frustrating. Though if you are starting a new project, you should definitely use the first style the style you and your team prefer.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

### #20Khatharr  Members

Posted 16 April 2013 - 03:51 PM

Personally I prefer the second style because it's the style I was trained with and I always feel 'jarred' when I see a whole line used up by an open brace. It just makes me want to scream 'Mottainaiiiiiiiiiiiiiiiiiiiii!'

That said, when alone you do what you want. When you work with others do what they do.

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

if(condition) {
//dostuff on more
//than one line
}

vs

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


I never use 'braceless' blocks. To me it's just begging for trouble. On the other hand, I'll use that second style there so long as it doesn't make the longer than about 60 characters.

Oh, that's another thing. I'll break up compound statements to try to keep every line shorter than a certain length so that I don't have to mess with horizontal scrolling.

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.

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.