Sign in to follow this  
Chad Smith

Coding Style: Curly Braces

Recommended Posts

Chad Smith    1343

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?

Share this post


Link to post
Share on other sites
alvaro    21246
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.

Share this post


Link to post
Share on other sites
Cornstalks    7030
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

Share this post


Link to post
Share on other sites
stitchs_login    1361

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

Share this post


Link to post
Share on other sites
SimonForsman    7642
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
EddieV223    1839

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

Share this post


Link to post
Share on other sites
Chad Smith    1343

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.

Share this post


Link to post
Share on other sites

@EddieV223: huh.png

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

Share this post


Link to post
Share on other sites
NightCreature83    5002

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

Share this post


Link to post
Share on other sites
mhagain    13430

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.

Share this post


Link to post
Share on other sites
Amr0    2230
if( sOpinionQuery == "curly_braces_style_preference" )
{
	gamedev.curThread.post( this );
	gamedev.curThread.value += 0.02; // my two cents.
	gamedev.desiredFeatures += "forum polls";
}
else
	OneLiner();

Share this post


Link to post
Share on other sites
Musikai    138

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

Share this post


Link to post
Share on other sites
Azaral    467

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

Share this post


Link to post
Share on other sites
0r0d    1929

 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		 { /* ... */ }
}

Share this post


Link to post
Share on other sites
japro    887

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 :p

 

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

Share this post


Link to post
Share on other sites
Bacterius    13165

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.

Share this post


Link to post
Share on other sites
Khatharr    8812

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.

Share this post


Link to post
Share on other sites

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'. wink.png 

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

Share this post


Link to post
Share on other sites
L. Spiro    25615

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

Share this post


Link to post
Share on other sites
Khatharr    8812

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

Share this post


Link to post
Share on other sites
dynamiteandy    119

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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this