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

Personally I find it stupid to have to add the break statement after each case. In languages derived from BASIC, such as VB.NET, that doesn't exist and it's more logical. IMO, what would be logical in C-based languages is to have each case enclosed in curly braces.
  • 0
Personally I find it stupid to have to add the break statement after each case. In languages derived from BASIC, such as VB.NET, that doesn't exist and it's more logical. IMO, what would be logical in C-based languages is to have each case enclosed in curly braces.

I tend to put all my switch(..) cases within there own braces. makes it easier to see grouped statements.

  • 0
Personally I find it stupid to have to add the break statement after each case. In languages derived from BASIC, such as VB.NET, that doesn't exist and it's more logical. IMO, what would be logical in C-based languages is to have each case enclosed in curly braces.

The benefit of the break; statement is that is gives C/C++ (Not C# for whatever reason) the ability to fall from one case to another. For example:

int myVar = 0;
cin >> myVar;

switch(myVar)
{
    case 0:
        MyFunc();
        break;
    case 1:
        Foo();
    case 2:
        Bar();
        break;
}

If the user inputs 0, then MyFunc is executed, if the user inputs 1, then Foo AND Bar are executed, and if the user inputs 2, then only Bar is executed. This is very useful in certain situations, especially when cases are very similar, but not identical.

  • 0
The benefit of the break; statement is that is gives C/C++ (Not C# for whatever reason) the ability to fall from one case to another. For example:

int myVar = 0;
cin >> myVar;

switch(myVar)
{
    case 0:
        MyFunc();
        break;
    case 1:
        Foo();
    case 2:
        Bar();
        break;
}

If the user inputs 0, then MyFunc is executed, if the user inputs 1, then Foo AND Bar are executed, and if the user inputs 2, then only Bar is executed. This is very useful in certain situations, especially when cases are very similar, but not identical.

That's true, but I don't see why you just can't do:

Foo();

Bar();

Achieves the same functionality. Also, for people saying style 2 minimizes the number of lines...is there a reason you guys are trying to cut down on line count?

  • 0

I use the 1st style, but i can deal with the 2nd style in most cases. The problem i run into is when you have multi-line starters for the blocks, such as:

if ( myReallyLongObjectName.MyReallyLongFunctionNameOne() &&
	 myReallyLongObjectName.MyReallyLongFunctionNameOne() &&
	 myReallyLongObjectName.MyReallyLongFunctionNameOne() &&
	 myReallyLongObjectName.MyReallyLongFunctionNameOne() ) 
{

	 MyInsideFunctionCall();

}

if ( myReallyLongObjectName.MyReallyLongFunctionNameOne() &&
	 myReallyLongObjectName.MyReallyLongFunctionNameOne() &&
	 myReallyLongObjectName.MyReallyLongFunctionNameOne() &&
	 myReallyLongObjectName.MyReallyLongFunctionNameOne() ) {

	 MyInsideFunctionCall();

}

I feel like the 1st way (And 1st style) more clearly separates the inside of the if-block from the conditions. In the 2nd style, you pretty much have to just look for the whitespace, which seems pretty improper (esp. considering it may not even be there!)

  • 0
That's true, but I don't see why you just can't do:

Foo();

Bar();

Achieves the same functionality. Also, for people saying style 2 minimizes the number of lines...is there a reason you guys are trying to cut down on line count?

True, but if you've got (for example) 20 case statements that all have common code, then it is easier to maintain the code if the common code is only written once. For example, if you've got 20 lines of common code between 5 case statements, you've got the same code written 5 times, which means it takes 5x longer to maintain should you need to adjust something in the common code as well as the code added by the other cases, whereas if you're case statements fall through, you decrease line count and make your code more maintainable.

I think (but don't hold me to this, it's a long time since I've studies low level) that repeating code also uses more memory when running the executable, as the program needs to store more instructions, negligible in the modern day? yes, but it's a slippery slope.

That said though, there is less risk of error through not falling through cases. I can't count the amount of times I've left a break; statement out with disastrous consequences! :laugh:

  • 0
Personally I find it stupid to have to add the break statement after each case. In languages derived from BASIC, such as VB.NET, that doesn't exist and it's more logical. IMO, what would be logical in C-based languages is to have each case enclosed in curly braces.

The reason for the break statement is because C allows a fall-through behavior, which is similar to specifying multiple values to match a single case in VB:

Select Case variable
  Case 1, 3, 5, 7, 9
	Debug.WriteLine("Your number was odd!")
  Case 0, 2, 4, 6, 8
	Debug.WriteLine("Your number was even!")
  Case Else
	Debug.WriteLine("Your number wasn't between 0 and 9 inclusive!")
End Select

C/C++:

switch (variable)
  {
	case 1:
	case 3:
	case 5:
	case 7:
	case 9:
	  puts("Your number was odd!");
	break;

	case 0:
	case 2:
	case 4:
	case 6:
	case 8:
	  puts("Your number was even!");
	break;

	default:
	  puts("Your number wasn't between 0 and 9 inclusive!");
  }

Why isn't there a break statement after the default case? I could ask something similar about BASIC - why isn't there an End Case statement?

While the example is rather ridiculous, especially since you can use a remainder operator on the switch/Select Case parameter to end up with fewer cases to test in this specific example, it does illustrate a similarity. I suppose a mathematical set notation could have been used in C to make it more BASIC-like (it would be a new array, basically), but that isn't the way C works.

The idea regarding using braces to denote the beginnings and endings of case statements in C isn't a bad idea:

switch (variable)
  {
	case 0:
	case 2:
	  {
		//code
	  }

	default:
	  {
		//code
	  }
  }

So the suggestion made about using braces to denote the beginnings and endings of cases could work while still allowing the fall-through mechanism. Doing such a thing would make parsing the code a bit harder.

Part of the reason the break statement is so useful in this case is because of the fact that it is easier to NOT check for an ending delimiter. The break statement isn't actually the end of a case. The end of a case is undelimited. The break statement is simply used to exit the switch statement. ^_^

However, I personally prefer Python over any other programming language (except for Web programming, where I use PHP).

  • 0

There's nothing stopping you putting additional braces into C or C++ code. In fact, this can be a very good thing, as the compiler can make some very nice code adjustments for you because you're explicitly telling it that certain variables are only used in smaller blocks, thus it may be able to keep that variable inside a register or whatever for a little performance boost.

Likewise, there's nothing stopping you from using braces in a switch statement, in fact sometimes I just do this for the sake of readability.

You do have to be careful, though, too many braces and you'll find yourself scrolling to the right of your code, which is a very bad thing.

Anyway, on topic, I use the first method of braces. To me, it makes a lot more sense, it makes the code more readable and explicitly shows the flow and scope of the code. Some people complain about the lack of vertical screen space, but in this day and age with your high-resolution, 24" wide-screen monitors, it's not really an issue. Plus due to my eyesight, I have to keep the font up pretty high anyway, so loosing an extra line isn't going to make much difference.

Each to their own, though, anything thing to remember is that if you're working in groups, forget about what you do, do what everyone else does as consistent code is better than inconsistent code with tiny bits of consistency that you can read.

  • 0

I actually switched from the second style to the first style recently. I find it much more readable EXCEPT for if/else statements. I much prefer having the opening brace on the same line as the last conditional statement as it implies a link between each branch in a conditional statement set. But it's not that big of a deal.

The third style is just funky, and there are a few other styles I have run into. One type was a variation on #3:

languageStructure()
	  {
			   statement1;
			   statement2;
	  }

To me it seems like a complete waste of keystrokes and whitespace.

I see a lot of the second style in C and C++ code due to its connection with the original K&R C. It is all personal preference though. Use whatever suits you best or your team is using.

  • 0

For if/else statements, I just do this:

if (TRUE == blah)
{
   // Other stuff
}
else
{
   // Some stuff
}

I can see what you mean about if-elseif statements, that CAN get a bit untidy but usually if I have to have an ifelse statement, I'll try to use a switch instead as it's no slower than a bunch of if statements and looks much neater.

  • 0

I like using the second style because it's more compact and i find it eaier to read. That's the way i was taught and i like it because it doesn't waste any lines.

Although at work i've been told to use the first style because it's easier for other people to see the braces. However, for JS we use the second method in case of any semi-colon injection after the first line.

Either way, I use a text editor which highlights the matching braces so i don't have any problems with not seeing the braces properly.

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

    • No registered users viewing this page.
  • Posts

    • Which finger's fingernail are we talking about? I can see how not having this info can lead to massive differences in interpretation.
    • This Chinese company is reportedly developing a feature Apple and Samsung can only dream of by Hamid Ganji While companies like Apple and Samsung have been relatively conservative with their devices’ battery capacities in recent years, Chinese manufacturers have taken the competition to the next level by introducing significantly larger batteries. However, the latest report from China suggests that a local company may already be developing a smartphone with a whopping 14,000mAh battery. Chinese leaker Digital Chat Station claimed on Weibo that a smartphone maker is developing a device with a 14,000mAh battery. If true, it would be the largest battery ever used in a smartphone and could, in theory, provide up to a week of battery life on a single charge. The leaker did not reveal the name of the company behind the device, but there are some clues. This week, HONOR unveiled the X80 Pro Max in China with an 11,000mAh battery and 90W wired charging support. The company also launched the Honor Win in January, which packs a 10,000mAh battery. HONOR, a former subsidiary of Huawei, has a proven track record of developing smartphones with unusually large batteries. However, other Chinese brands, including Xiaomi, have also launched devices such as the Xiaomi 17 Pro Max with 7,500mAh batteries. Though Chinese users on Weibo also believe the company behind the new battery is HONOR. Interestingly, Digital Chat Station said the device with the 14,000mAh battery weighs around 220 grams, making it lighter than the Apple iPhone 17 Pro Max (233 grams) and slightly heavier than the Samsung Galaxy S26 Ultra (214 grams). The iPhone 17 Pro Max currently packs a 5,088mAh battery in eSIM-only versions, while the Galaxy S26 Ultra features a 5,000mAh battery. Neither device is expected to see a dramatic increase in battery capacity in its next-generation successor. So when it comes to battery comparison, Chinese brands are unbeaten. HONOR smartphones are currently available in the EU, but the Chinese brand has no official presence in the United States due to restrictions imposed by the U.S. government.
    • Qualcomm takes on NVIDIA with new Dragonfly CPU and AI chips by Pradeep Viswanathan Microsoft, Google, Amazon, AMD, Meta, Apple, OpenAI, and several others have been developing their own chips for AI infrastructure. However, NVIDIA still remains the dominant player in the market. Today, Qualcomm announced a major expansion of its data center infrastructure portfolio to better compete with NVIDIA. The new lineup includes the Qualcomm Dragonfly C1000 CPU, Qualcomm High Bandwidth Compute technology, the Dragonfly AI300 inference accelerator, new connectivity products, and custom silicon solutions. Qualcomm claims that this new lineup improves performance per watt, token throughput, and total cost of ownership for AI data centers. The Dragonfly C1000 is a new data center CPU built with Qualcomm’s custom Oryon cores. This chip will feature more than 250 cores, frequencies above 5GHz, and a chiplet-based design. Qualcomm claims that this new C1000 can deliver more than 2x better performance per watt compared to existing server CPU offerings based on specifications. The Dragonfly C1000 will support PCIe Gen 7 with more than 2TB/s of connectivity, along with CXL, advanced RAS features, and both air and liquid cooling. Qualcomm expects the Dragonfly C1000 to be commercially available in 2028. Additionally, Qualcomm and Meta announced a multi-year, multi-generation agreement under which Qualcomm will supply Dragonfly C1000 data center CPUs for Meta’s next-generation server fleet. Qualcomm also announced High Bandwidth Compute, a new near-memory computing architecture designed to address AI’s memory bandwidth bottleneck. HBC Gen 1 will debut with the Dragonfly AI250, which is expected to sample in mid-2027. The AI250 will deliver 133TB/s per card, an 18x increase in effective memory bandwidth compared to the AI200 with LPDDR5X. The new Dragonfly AI300 with HBC Gen 2 is a rack-level AI inference platform from Qualcomm. Qualcomm claims that the AI300 can deliver 4x to 8x better performance per watt compared to existing GPU-based architectures based on memory bandwidth per watt per card. The Dragonfly AI300 is expected to be available in 2028.
  • Recent Achievements

    • Week One Done
      Meta Plast earned a badge
      Week One Done
    • 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
  • Popular Contributors

    1. 1
      +primortal
      461
    2. 2
      +Edouard
      171
    3. 3
      PsYcHoKiLLa
      136
    4. 4
      Michael Scrip
      78
    5. 5
      Xenon
      77
  • Tell a friend

    Love Neowin? Tell a friend!