Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

code formatting - Unnecessary curly braces in C++?

When doing a code review for a colleague today I saw a peculiar thing. He had surrounded his new code with curly braces like this:

Constructor::Constructor()
{
   existing code

   {
      New code: do some new fancy stuff here
   }

   existing code
}

What is the outcome, if any, from this? What could be the reason for doing this? Where does this habit come from?

Edit:

Based on the input and some questions below I feel that I have to add some to the question, even though that I already marked an answer.

The environment is embedded devices. There is a lot of legacy C code wrapped in C++ clothing. There are a lot of C turned C++ developers.

There are no critical sections in this part of the code. I have only seen it in this part of the code. There are no major memory allocations done, just some flags that are set, and some bit twiddling.

The code that is surrounded by curly braces is something like:

{
   bool isInit;
   (void)isStillInInitMode(&isInit);
   if (isInit) {
     return isInit;
   }
}

(Don't mind the code, just stick to the curly braces... ;) ) After the curly braces there are some more bit twiddling, state checking, and basic signaling.

I talked to the guy and his motivation was to limit the scope of variables, naming clashes, and some other that I couldn't really pick up.

From my POV this seems rather strange and I don't think that the curly braces should be in our code. I saw some good examples in all the answers on why one could surround code with curly braces, but shouldn't you separate the code into methods instead?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's sometimes nice since it gives you a new scope, where you can more "cleanly" declare new (automatic) variables.

In C++ this is maybe not so important since you can introduce new variables anywhere, but perhaps the habit is from C, where you could not do this until C99. :)

Since C++ has destructors, it can also be handy to have resources (files, mutexes, whatever) automatically released as the scope exits, which can make things cleaner. This means you can hold on to some shared resource for a shorter duration than you would if you grabbed it at the start of the method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...