• 0

Curly braces placement and indentation


Question

Almost all the code I've seen until now uses the following style for curly braces:

void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}

Visual Studio also defaults to this. However I have read Code Complete 2nd edition and Steve McConnell argues against this style. "Avoid unindented being-end pairs (...) Although this approach looks fine, it (...) doesn't show the logical structure of the code. Used this way, the begin and end aren't part of the control construct, but they aren't part of the statements after it either." Steve McConnell recommends using the pure block style, which emulates Visual Basic (where there's no curly braces):

void swap(int &a, int &b) {
	int temp = a;
	a = b;
	b = temp;
}

or this (begin-end block boundaries):

void swap(int &a, int &b) 
	{
	int temp = a;
	a = b;
	b = temp;
	}

Although I tend to agree with McConnell's reasoning, all the books I read, the classes I attended, and Visual Studio, use the first style, so I find it a bit weird. What do you think?

Recommended Posts

  • 0

I use the second style for everything. Using the first style does not improve readability, it just adds an extra line. The second style is recommended by Sun for Java coding by the way. I don't think there are official recommendations from ANSI/ISO for C/C++ so I use the second style for that.

  • 0
Why would you even bother with the braces?

I prefer style 1, so much nicer to read and have braces that line up. I don't like why people use braces for one line if statements as well, looks horrendous.

Because there's two statements in that while loop :)

  • 0
...

i can see the second line is wrongly indented but its part of the if condition code, if the { bracket was on the if line i could easily miss that and think the code for the if condition being true is only one line

That's why I use a text editor that does bracket highlighting, I can see quite quickly if I've got an extra, or a missing bracket.

  • 0
I use the first for everything bar CSS where I use the 2nd. If I am doing an if with one response:

if ($x == $y)

{echo "hello";}

I'll do it on one line.

Why not just do it all on one line?

if ($x == $y) echo "hello";

It's bad practice anyway, though, because it means more work for any future coders, you should always brace and indent properly even for single lines.

  • 0

I use and prefer the second style. If I'm given code in the first I change it, that's how much it annoys me. It's not rational, just how I learnt :p

Why would you even bother with the braces?

I prefer style 1, so much nicer to read and have braces that line up. I don't like why people use braces for one line if statements as well, looks horrendous.

If you are reading someone else's code the brackets allow you to very easily what goes where in terms of the if statement and others that come after it. It just makes it easier to read, and code is never going to win a beauty competition.

  • 0

I use the second style, but I have no issues using the first, and have done so for a few of my projects.

... It just makes it easier to read, and code is never going to win a beauty competition.

Unless of course, there was a beauty contest for code :p

  • 0
I use and prefer the second style. If I'm given code in the first I change it, that's how much it annoys me. It's not rational, just how I learnt :p

If you are reading someone else's code the brackets allow you to very easily what goes where in terms of the if statement and others that come after it. It just makes it easier to read, and code is never going to win a beauty competition.

If the statement is one line then that wouldn't pose a problem.

Rahhhh;

if (blah blah)
   doSomething()
else
   doOtherThing

Yeahhhh;

With well used line spacing there is no need to use the braces here unless you plan on adding more code. It adds unwanted mess. Generally, I can make code that is very easy to follow, read and even looks good, depending on the language. DirectX is a pain to get looking remotely nice.

  • 0

First style is called BSD style (has other name, if I remember it's one hackers name) and second style is called K&R (people who contributed/created C) and the last one looks like GNU style.

For personal usage I use first and something the second. But it depends on what work you are doing and the coding standard you must use then coding.

  • 0

The last form is indeed GNU style. I recently had to edit some gcc source code to get it to compile the way I wanted it to compile (following LinuxFromScratch). I looked into the source files and found that style.

I use the first form for C/C++/C# code, and I use the second form for PHP, Java, JS and CSS.

In addition, I've adopted my own form for one-liners:

if (condition)
	{ result; }

except with CSS, where I use:

.rule_target { property: propertyValue; }

For some reason, people find my personal conventions really unusual... :p

Edit:

In addition, I was looking through some source code about a month ago, and I found this crazy form:

if (condition)
{   code1;
	code2;
	}

Also, there are different variations when it comes to case statements:

switch (item)
{
	case 0:
		code0;
	break;

	case 1:
		code1;
		break;
}

Notice how the break statements are in different places? Also, when you create variables in case statements, braces are required (at least in C/C++). In that case, does the break statement go inside or outside of the braces? *sigh* Too many conventions! :D

Edit2:

The first form is indeed BSD style, also known as Allman style. Wikipedia has a great article on indent style.

Edited by rpgfan
  • 0

Having programmed in many languages.. readibility, maintainability, and screen compactness are my key considerations.

Style 1 simply wastes too much vertical space, expecially it Get/Set section.

Style 2 is not symetrical, and looks awkward (IMHO)

I use two basic rules.

1) For normal code blocks, I use a modified Style 1, but a little tighter.

if (condition)
{   code1;
    code2;
} //if

Note: the "//if" is automatically added with a VS add-in

This gives the std left aligned {} that most developers are use to.

Displays the actual code in an easily read block.

Yes, it only saves 1 line per block, but it does add up.

2) One liners go on one line

But I add the {} in case someone else needs to add something later.

Remember: We write code once, others maintain forever..

if ($x == $y)
{    echo "hello";}

//easily becomes...
if ($x == $y)
{    echo "hello";
     echo "hello again";
} //if


Note: the "// if" is automatically added with a VS add-in

This works well for me. :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Look up "greed". If you are willing to buy that it's only inflation, I've got a bridge to sell you.
    • Very umm, blue?  
    • Steam Summer Sale 2026 kicks off offering weeks of PC game discounts by Pulasthi Ariyasinghe Every year, one of the biggest events that Valve hosts is the Steam Summer Sale. Now, the 2026 edition has just kicked off, bringing discounts for everything from the newest games and retro gems to all sorts of DLC packs. As always though, PC gaming hordes have managed to shake the servers of Steam just as the sale opened its doors, so expect the prices, store pages, and services to not show up properly for some time till the backend stabilizes. You'll find sales being present, though with minor cuts, for even relatively recently released titles this time. The front page is the place to be for anyone looking for recommendations, with it putting a spotlight on fresh games every day. However, keep in mind that the discounts themselves will not be changing and will remain static throughout the sale. Blockbusters like Clair Obscur Expedition 33, Split Fiction, Red Dead Redemption II, Battlefield 6, Dispatch, Baldur's Gate 3, Resident Evil Requiem, Anno 117, Arc Raiders, Black Ops 7, Kingdom Come: Deliverance II, and much more are currently discounted. Valve has also brought back the special "Deep Discounts" section. While part of this same sale, it only highlights games that are discounted by at least 85%, with some titles even reaching 95% off. Some of the games included here are The Witcher 3: Wild Hunt, Watch Dogs 2, Far Cry 4, Wreckfest, Dragon Ball Xenoverse 2, The Quarry, Ghostwire Tokyo, Call of Duty: Modern Warfare II, and much more for just a few dollars each. The Steam Summer Sale of 2026 will be open for business until July 9, giving everyone two whole weeks to try and keep their wallets closed. If you want to see the biggest highlights, be sure to read our Weekend PC Game Deals special coming this Saturday.
    • Digisecret 2.1.431 Pro and Wzipse 4.0. Both are encrypted self-extracting archives.
    • Google reshuffles its AI coding team as it struggles to catch Anthropic by Karthik Mudaliar Google is already reorganizing the AI coding “strike team” it created roughly two months ago, as it attempts to find ways to close the gap with Anthropic in one of generative AI’s most commercially important areas. According to The Information, Google DeepMind is expanding the team’s focus to include “midtraining,” rather than concentrating only on coding tools and agents. Midtraining takes place after a model’s broad initial training but before the final stages that prepare it to follow instructions and perform specific tasks. In simple terms, it gives developers another opportunity to expose a model to carefully selected data before it is polished for release. That could help Google improve Gemini’s underlying coding abilities instead of relying only on better prompts, interfaces, or post-training. Previous research has found that midtraining can be particularly effective for code and mathematics, where models must move from general language knowledge to more structured tasks. Google reportedly created the original strike team in April. It was led by Google DeepMind research engineer Sebastian Borgeaud, who previously worked on model pretraining, and focused on complex, long-running programming jobs. Google co-founder Sergey Brin and Google DeepMind chief technology officer Koray Kavukcuoglu were also reportedly involved in the effort. DeepMind researchers were said to believe that Anthropic’s coding tools were outperforming Google’s Gemini models, prompting the company to give the project more attention. Anthropic has made coding a central part of its AI strategy through Claude Code and its Claude model family. The company has continued improving that area, with Claude Opus 4.8 offering upgrades for coding and other agentic tasks, along with the now-unavailable Mythos and Fable models. The reshuffle also comes at a time when Google faces increased competition for AI researchers. Gemini co-lead Noam Shazeer recently announced that he was leaving Google for OpenAI, while two other researchers who contributed to Gemini and DeepMind projects are reportedly preparing to join Anthropic. It remains unclear whether the reorganized team will produce a new public Gemini model or developer product. No release date, team size, or specific performance target has been disclosed. Source: The Information
  • Recent Achievements

    • First Post
      kinowa earned a badge
      First Post
    • Rookie
      krychek57 went up a rank
      Rookie
    • Grand Master
      Jaybonaut went up a rank
      Grand Master
    • One Year In
      Philsl earned a badge
      One Year In
    • Dedicated
      Scoobystu earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      416
    2. 2
      +Edouard
      168
    3. 3
      PsYcHoKiLLa
      132
    4. 4
      Xenon
      73
    5. 5
      Michael Scrip
      73
  • Tell a friend

    Love Neowin? Tell a friend!