• 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

    • ahh yes the good old your opinion differs from mine so you are therefore insane lol destiny 1 had no agenda pushing and was a massive success of a game, if you clearly look online the team for some reason thought they had too many men on the team and went on a woman and dei recruitment drive and we all know how destiny 2 performed from then on in
    • The limited imaginations and business acumen of non-dominant players is simply that: the abject lack of creative business acumen. Businesses often want to operate in a financially-rewarding marketplace (free market economics) and/or exit/cash-out at maximal financial recompense. Money is their incentive; regulations are both their obstacles and their tools; politics is their means of influencing the marketplace. Google, in this story's example, is crying that AWS and Azure are "too dominant" -- cuz Google Cloud is not printing as much money as Alphabet wants (although it is still dramatically more than they actually need). The EU DMA should truly follow-the-money and treat the EU as its own sovereign nation in order to protect European market players: Domestic entities are exempt from market-influence regulations until absolute monopoly is achieved; Foreign (non-EU/non-Euro) entities are all regulated via stricter DMA measures whereby regulated partnership with independent domestic entity becomes the only way for foreign entities to 'tip the scale' for favorable financial remunerations. Basically create a dual-track aligning with China's foreign investment models. In my eyes, this is the only way to properly protect the European marketplace beyond the current dot-com/ai-bubble/social-media crazes.
    • I have a fire n ice theme w my bedroom laptops. one is a red lenovo gaming laptop (fire) and the precision is ice
    • Adobe Acrobat Reader DC 2026.001.21691 by Razvan Serea Adobe Acrobat Reader DC software is the free, trusted standard for viewing, printing, signing, and annotating PDFs. Its the only PDF viewer that can open and interact with all types of PDF content – including forms and multimedia. It’s connected to Adobe Document Cloud – so you can work with PDFs on computers and mobile devices. Adobe Document Cloud is a revolutionary, modern and efficient way to get work done with documents in the office, at home or on-the-go. At the heart of Document Cloud is the all-new Adobe Acrobat DC, which will take e-signatures mainstream by delivering free e-signing with every individual subscription. Document Cloud includes a set of integrated services that use a consistent online profile and personal document hub. With Adobe Document Cloud, people will be able to create, review, approve, sign and track documents whether on a desktop or mobile device. Businesses will be able to take advantage of Document Cloud for enterprise which provides enterprise-class document services that integrate into systems of record such as CRM, HCM, CLM, and CMS, adding speed, efficiency and transparency to getting business done with documents. Adobe Acrobat Reader DC new feature highlights: Work with PDFs from anywhere with the new, free Acrobat DC mobile app for Android or iOS. Select functionality is also available on Windows Phone. Use the new Fill & Sign tool in your desktop software to complete PDF forms fast with smart autofill. Download the free Adobe Fill & Sign mobile app to add the same option to your iPad or Android tablet device. Save money on ink and toner when printing from your Windows PC. Store and access files in Adobe Document Cloud with 5GB of free storage. Get instant access to recent files across desktop, web, and mobile devices with Mobile Link. Sync your Fill & Sign autofill collection across desktop, web, and iPad devices. Adobe PDF Pack premium features includes: Convert documents and images to PDF files. Use your mobile device camera to take a picture of a paper document or form and convert it to PDF. Turn PDFs into editable Microsoft Word, Excel, PowerPoint, or RTF files. Combine multiple files into a single PDF (web only). Get signatures from others with a complete e-signature service. Send, track, and confirm delivery of documents electronically instead of using fax or overnight services (tracking not available on mobile). Store and access files online with 20GB of storage. Download: Adobe Acrobat Reader DC 64-bit | 719.0 MB (Freeware) Link: Adobe Acrobat Reader DC Home Page | Release Notes | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • 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
      404
    2. 2
      +Edouard
      172
    3. 3
      PsYcHoKiLLa
      131
    4. 4
      Xenon
      72
    5. 5
      Michael Scrip
      71
  • Tell a friend

    Love Neowin? Tell a friend!