• 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

    • Calibre 9.10 by Razvan Serea  Calibre is an open source e-book library management application that enables you to manage your e-book collection, convert e-books between different formats, synchronize with popular e-book reader devices, and read your e-books with the included viewer. It acts as an e-library and also allows for format conversion, news feeds to e-book conversion, as well as e-book reader sync features and an integrated e-book viewer. Calibre's features include: library management; format conversion (all major ebook formats); syncing to e-book reader devices; fetching news from the Web and converting it into ebook form; viewing many different e-book formats, giving you access to your book collection over the internet using just a browser. Calibre 9.10 changelog: New features Content server: A new "modern" interface with a sidebar to ease navigation Content server: When used with HTTPS allow installation as a PWA (Progressive Web App) Edit book: Saved searches: When filtering the list of saved searches match by keywords CSS parsing: Add support for CSS Level 4 selectors Cover grid: When using an image larger than the viewport as a texture scale it to fit the viewport Annotations browser: Allow restricting displayed annotations by custom annotation styles as well Edit book: Compress images: Add option to convert PNG images to JPEG or WEBP Bug fixes E-book viewer: Fix IME on Windows not working when typing in notes for highlights Conversion: Heuristics: Improve performance in some pathological cases SNB Input: Fix error on some input files Windows: fix rare crash when too many notifications are displayed at once Fix duplicating of books not duplicating value from enumerated columns when the column has a default value defined Fix a regression in 9.8 that caused errors from AI plugin providers to be silently swallowed and not displayed to user Fix CSV export invalid when exporting comments field Disallow Python templates when reading book metadata (CVE-2026-53511) Improved news sources The Week Economist Espresso Horizons Download: Calibre 9.10 | Portable | ~200.0 MB (Open Source) Download: Calibre for MacOS | 327.0 MB Download: Calibre for Linux View: Calibre Home Page | Calibre Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Malwarebytes Anti-Malware 5.6.1.257 by Razvan Serea Malwarebytes is a high performance anti-malware application that thoroughly removes even the most advanced malware and spyware. Malwarebytes version 5.**** brings comprehensive protection against today’s threat landscape so that you can finally replace your traditional antivirus. You can finally replace your traditional antivirus, thanks to a innovative and layered approach to prevent malware infections using a healthy combination of proactive and signature-less technologies. While signatures are still effective against threats like potentially unwanted programs, the majority of malware detection events already come from signature-less technologies like Malwarebytes Anti-Exploit and Malwarebytes Anti-Ransomware; that trend will only continue to grow. For many of you, this is something you already know, since over 50% of the users already run Malwarebytes as their sole security software, without any third-party antivirus. What's new in Malwarebytes 5.****: Unified user experience - For the first time, Malwarebytes now provides a consistent experience across all of our desktop and mobile products courtesy of an all new and reimagined user experience powered by a faster and more responsive UI all managed through an intuitive dashboard. Modern security and privacy integrations - Antivirus and ultra-fast VPN come together seamlessly in one easy-to-use solution. Whether you’re looking for a next-gen VPN to secure your online activity, or harnessing the power of Browser Guard to block ad trackers and scam sites, taking charge of your privacy is simple. Trusted Advisor - Empowers you with real-time insights, easy-to-read protection score and expert guidance that puts you in control over your security and privacy. Malwarebytes 5.6.1.257 changelog: Features and improvements Updated the sign-in section of the My Subscription page to clarify that users can activate their subscription by signing in with their Malwarebytes account. Updated the uninstall flow to collect more meaningful insights and address customer concerns. Refreshed the app's tutorial layout for a better look and feel. Issues fixed Fixed an outdated link when clicking Take action after running a Digital Footprint Scan. Miscellaneous bug fixes. Download: Malwarebytes 5.6.1.257 | 472.0 MB (Free, paid upgrade available) Links: Malwarebytes Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Yep, not sure where the surprise is here. They release a new model for every phone, every year
    • AI would probably be better utilised replacing Executives than Engineers.
    • RapidRAW 1.5.8 by Razvan Serea RapidRAW is a beautiful, non-destructive, GPU‑accelerated RAW image editor designed for speed and simplicity. It uses a lightweight (~30 MB), efficient code base built with Rust, React and Tauri. Ideal for Lightroom workflows, it offers rich editing tools—exposure, contrast, highlights, shadows, whites/blacks, tone curves, HSL mixer, dehaze, vignetting, film grain, sharpening, clarity and noise reduction—processed in real-time on the GPU. Features include intuitive masking (brush, linear, radial, AI-powered subject and foreground detection), generative edit layers (via ComfyUI), 32‑bit precision, and full RAW format support through rawler. RapidRAW also provides library management (folder navigation, ratings, metadata, EXIF viewer), batch operations, export presets (JPEG/PNG/TIFF), sidecar editing (.rrdata), undo/redo history, customizable UI themes, smooth animations, resizable panels, and preset copy/paste. A modern high-performance Lightroom alternative with polished UX and creative tools, RapidRAW brings powerful photo editing to photographers seeking speed, responsive GPU feedback, and streamlined workflows. RapidRAW v1.5.8 release notes: This release introduces several new editing tools and workflow refinements designed to improve both photo editing and library management. It expands creative flexibility with the addition of a preset intensity slider and a global hue adjustment, while also introducing convenient navigation features such as quick bottom bar filters and folder sorting. Behind the scenes, the update addresses background indexing issues and ensures folder image counts are updated correctly. It also broadens accessibility by adding support for Korean and Traditional Chinese. [full changelog] Download: RapidRAW 1.5.8 | ARM64 | ~20.0 MB (Open Source) View: RapidRAW Home Page | Screenshot | Other operating systems Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      xvvxcvv earned a badge
      Week One Done
    • One Month Later
      xvvxcvv earned a badge
      One Month Later
    • Enthusiast
      Xonos went up a rank
      Enthusiast
    • Conversation Starter
      Admir earned a badge
      Conversation Starter
    • First Post
      The_Focal_Point earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      405
    2. 2
      +Edouard
      168
    3. 3
      PsYcHoKiLLa
      129
    4. 4
      neufuse
      69
    5. 5
      Xenon
      68
  • Tell a friend

    Love Neowin? Tell a friend!