Followers 0

# Coding Style: Curly Braces

## 73 posts in this topic

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?

0

##### Share on other sites

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
0

##### Share on other sites
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
2

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

##### Share on other sites

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
0

##### Share on other sites

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.

0

##### Share on other sites

@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
0

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

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
0

##### Share on other sites

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.

2

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

0

##### Share on other sites

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
0

##### Share on other sites

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

0

##### Share on other sites

What about using the best of both worlds?

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



1

##### Share on other sites

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)

0

##### Share on other sites

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.

0

##### Share on other sites

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.

0

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

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
0

##### Share on other sites

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
0

##### Share on other sites

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

0

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

2

## Create an account

Register a new account