ChatGPT解决这个技术问题 Extra ChatGPT

What's the purpose of using braces (i.e. {}) for a single-line if or loop?

I'm reading some lecture notes of my C++ lecturer and he wrote the following:

Use Indentation // OK Never rely on operator precedence - Always use parentheses // OK Always use a { } block - even for a single line // not OK, why ??? Const object on left side of comparison // OK Use unsigned for variables that are >= 0 // nice trick Set Pointer to NULL after deletion - Double delete protection // not bad

The 3rd technique is not clear to me: what would I gain by placing one line in a { ... }?

For example, take this weird code:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0)
    {
        j++;
    }
}

and replace it with:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;

What's the benefit of using the 1st version?

Readability and maintainablity. It's not immediately obvious what statement block 'j++' belongs to, and that adding code after it won't be associated with the if statement.
I was always told to use the curly braces {} for these lines for a couple of reasons. It makes the code clearer to read. Also someone else in six months time may need to edit your code so clarity is important and with the braces there an error is less likely to happen. There's nothing techincally more correct about it, it's more just a matter of good practice. Keep in mind a project may have thousands and thousands of lines of code for some new guy to plought through!
I don't agree with 6, as it will hide a double deletion and potentially hide logic errors.
#5 might be tricky - consider this loop: for (unsigned i = 100; i >= 0; --i).
Btw, (i % 2 == 0) contradicts (2). You are relying on operator precedence, and the meaning is of course ((i % 2) == 0) rather than (i % (2 == 0)). I would classify rule 2 as "a valid sentiment but 'always' is wrong".

C
Community

Let's attempt to also modify i when we increment j:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
        i++;

Oh no! Coming from Python, this looks ok, but in fact it isn't, as it's equivalent to:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
i++;

Of course, this is a silly mistake, but one that even an experienced programmer could make.

Another very good reason is pointed out in ta.speot.is's answer.

A third one I can think of is nested if's:

if (cond1)
   if (cond2) 
      doSomething();

Now, assume you now want to doSomethingElse() when cond1 is not met (new feature). So:

if (cond1)
   if (cond2) 
      doSomething();
else
   doSomethingElse();

which is obviously wrong, since the else associates with the inner if.

Edit: Since this is getting some attention, I'll clarify my view. The question I was answering is:

What's the benefit of using the 1st version?

Which I have described. There are some benefits. But, IMO, "always" rules don't always apply. So I don't wholly support

Always use a { } block - even for a single line // not OK, why ???

I'm not saying always use a {} block. If it's a simple enough condition & behavior, don't. If you suspect someone might come in later & change your code to add functionality, do.


@Science_Fiction: True, but if you add i++ before j++, then both variables will still be in scope when they're used.
This sounds very reasonable, but neglects the fact that the editor does the indentation, not you, and it will indent the i++; in a way that shows immediately that it is not part of the loop. (In the past, this might have been a reasonable argument, and I've seen such problems. About 20 years ago. Not since.)
@James: that's not a "fact", though, it's your workflow. And the workflow of a lot of people, but not of everyone. I don't think it's necessarily an error to treat C++ source as a plain text file, rather than the output of a WYSIWYG editor (vi/emacs/Visual Studio) that enforces formatting rules. So this rule is editor-agnostic beyond what you need, but not beyond what people actually use to edit C++. Hence "defensive".
@JamesKanze Are you really relying on the assumption that everyone always works in powerful IDEs? The last C I wrote was in Nano. Even given that, one of the first things I tend to turn off in an IDE is the auto-indentation - because the IDE tends to get in the way of my non-linear workflow, trying to correct my 'mistakes' based on incomplete information. IDEs aren't very good at auto-indenting every programmer's natural flow. Those programmers who use such features tend to merge their style to their IDE, which is fine if you only use one IDE but notsomuch if you work across many.
“this is a silly mistake, but one that even an experienced programmer could make.” – Like I said in my answer, I don’t believe that. I think it’s an entirely contrived case which doesn’t pose a problem in reality.
B
BlueRaja - Danny Pflughoeft

It's very easy to accidentally change control-flow with comments if you do not use { and }. For example:

if (condition)
  do_something();
else
  do_something_else();

must_always_do_this();

If you comment out do_something_else() with a single line comment, you'll end up with this:

if (condition)
  do_something();
else
  //do_something_else();

must_always_do_this();

It compiles, but must_always_do_this() isn't always called.

We had this issue in our code base, where someone had gone in to disable some functionality very quickly before release. Fortunately we caught it in code review.


Ohh boy!! it's defined behavior that must_always_do_this(); will execute if you comment //do_something_else();
@Supr, as it was first written, he's saying it's difficult to break the correct flow if you use braces, and then gives an example of how easy it is to break without having the code properly bracketed
I ran into this just the other day. if(debug) \n //print(info);. Basically took out a whole library.
Fortunately we caught it in code review. Ouch! That sounds so wrong. Fortunately we caught it in unit tests. would be much better!
@BЈовић But what if the code was in a unit test? The mind boggles. (Just kidding, it's a legacy app. There are no unit tests.)
Я
ЯegDwight

I have my doubts as to the competence of the lecturer. Considering his points:

OK Would anyone really write (or want to read) (b*b) - ((4*a)*c)? Some precedences are obvious (or should be), and the extra parentheses just add to confusion. (On the other hand, you _should_ use the parentheses in less obvious cases, even if you know that they're not needed.) Sort of. There are two wide spread conventions for formatting conditionals and loops: if ( cond ) { code; } and: if ( cond ) { code; } In the first, I'd agree with him. The opening { is not that visible, so it's best to assume it's always there. In the second, however, I (and most of the people I've worked with) have no problem with omitting the braces for a single statement. (Provided, of course, that the indentation is systematic and that you use this style consistently. (And a lot of very good programmers, writing very readable code, omit the braces even when formatting the first way.) NO. Things like if ( NULL == ptr ) are ugly enough to hinder readability. Write the comparisons intuitively. (Which in many cases results in the constant on the right.) His 4 is bad advice; anything which makes the code unnatural makes it less readable. NO. Anything but int is reserved for special cases. To experienced C and C++ programmers, the use of unsigned signals bit operators. C++ doesn't have a real cardinal type (or any other effective subrange type); unsigned doesn't work for numeric values, because of the promotion rules. Numerical values on which no arithmetic operations would make sense, like serial numbers, could presumably be unsigned. I'd argue against it, however, because it sends the wrong message: bitwise operations don't make sense either. The basic rule is that integral types are int, _unless_ there is a significant reason for using another type. NO. Doing this systematically is misleading, and doesn't actually protect against anything. In strict OO code, delete this; is often the most frequent case (and you can't set this to NULL), and otherwise, most delete are in destructors, so you can't access the pointer later anyway. And setting it to NULL doesn't do anything about any other pointers floating around. Setting the pointer systematically to NULL gives a false sense of security, and doesn't really buy you anything.

Look at the code in any of the typical references. Stroustrup violates every rule you've given except for the first, for example.

I'd suggest that you find another lecturer. One who actually knows what he's talking about.


The number 4 might be ugly however there is a purpose to it. It is trying to prevent if (ptr = NULL). I don't think I have ever used delete this, is it more common than I have seen? I don't tend to think setting a pointer to NULL after use is that bad of a thing to do but YMMV. Maybe it's just me but most of his guidelines don't seem that bad.
@Firedragon: Most compilers will warn about if (ptr = NULL) unless you write it as if ((ptr = NULL)). Have to agree with James Kanze that the ugliness of having NULL first makes it a definite NO for me.
@JamesKanze: I'd have to say that I disagree with most of what you've stated here - although I appreciate and respect your arguments for arriving at them. To experienced C and C++ programmers, the use of unsigned signals bit operators. - I don't agree at all: The use of bit operators signals the use of bit operators. To me, the use of unsigned indicates an aspiration on the part of the programmer that the variable should represent only positive numbers. Mixing with signed numbers will usually cause a compiler warning which was probably what the lecturer was intending.
To experienced C and C++ programmers, the use of unsigned signals bit operators Or not. size_t, anyone?
@James Kanze, consider the purpose. You are comparing code produced by an experienced programmer to instructional examples. These rules are provided by the lecturer because they are the kinds of mistakes he sees his students make. With experience, the students can relax or disregard these absolutes.
P
Peter Mortensen

All the other answers defend your lecturer’s rule 3.

Let me say that I agree with you: the rule is redundant and I wouldn’t advise it. It’s true that it theoretically prevents errors if you always add curly brackets. On the other hand, I’ve never encountered this problem in real life: contrary to what other answers imply, I’ve not once forgotten to add the curly brackets once they became necessary. If you use proper indentation, it becomes immediately obvious that you need to add curly brackets once more than one statement is indented.

The answer by Component 10 actually highlights the only conceivable case where this could really lead to an error. But on the other hand, replacing code via regular expression always warrants enormous care anyway.

Now let’s look at the other side of the medal: is there a disadvantage to always using curly brackets? The other answers simply ignore this point. But there is a disadvantage: it takes up a lot of vertical screen space, and this in turn can make your code unreadable because it means you have to scroll more than necessary.

Consider a function with a lot of guard clauses at the beginning (and yes, the following is bad C++ code but in other languages this would be quite a common situation):

void some_method(obj* a, obj* b)
{
    if (a == nullptr)
    {
        throw null_ptr_error("a");
    }
    if (b == nullptr)
    {
        throw null_ptr_error("b");
    }
    if (a == b)
    {
        throw logic_error("Cannot do method on identical objects");
    }
    if (not a->precondition_met())
    {
        throw logic_error("Precondition for a not met");
    }

    a->do_something_with(b);
}

This is horrible code, and I argue strongly that the following is vastly more readable:

void some_method(obj* a, obj* b)
{
    if (a == nullptr)
        throw null_ptr_error("a");
    if (b == nullptr)
        throw null_ptr_error("b");
    if (a == b)
        throw logic_error("Cannot do method on identical objects");
    if (not a->precondition_met())
        throw logic_error("Precondition for a not met");

    a->do_something_with(b);
}

Similarly, short nested loops benefit from omitting the curly brackets:

matrix operator +(matrix const& a, matrix const& b) {
    matrix c(a.w(), a.h());

    for (auto i = 0; i < a.w(); ++i)
        for (auto j = 0; j < a.h(); ++j)
            c(i, j) = a(i, j) + b(i, j);

    return c;
}

Compare with:

matrix operator +(matrix const& a, matrix const& b) {
    matrix c(a.w(), a.h());

    for (auto i = 0; i < a.w(); ++i)
    {
        for (auto j = 0; j < a.h(); ++j)
        {
            c(i, j) = a(i, j) + b(i, j);
        }
    }

    return c;
}

The first code is concise; the second code is bloated.

And yes, this can be mitigated to some extent by putting the opening brace on the previous line. So: if you insist on curly braces, at least put the opening brace on the previous line.

In short: don’t write unnecessary code which takes up screen space.

In the time since originally writing the answer I’ve mostly accepted the prevailing code style and use braces unless I can put the entire single statement on the previous line. I still maintain that not using redundant braces is usually more readable, and I have still never encountered a bug caused by this.


If you don't believe in writing code that takes up screen space unnecessarily, then you have no business putting the opening brace on its own line. I'm probably now going to have to duck and run from the holy vengeance of GNU, but seriously -- either you want your code to be vertically compact, or you don't. And if you do, don't do things designed solely to make your code less vertically compact. But as you say, having fixed that, you'd still also want to remove redundant braces. Or perhaps just write if (a == nullptr) { throw null_ptr_error("a"); } as one line.
@Steve As a matter of fact, I do put the opening brace on the previous line, for the very reason you stated. I used the other style here to make it more obvious how extreme the difference can be.
+1 I completely agree that your first example is much easier to read without braces. In the second example, my personal coding style is to use braces on the outer for-loop and not on the inner. I disagree with @SteveJessop about having to be one extreme or the other about vertically compact code. I omit extra braces with one-liners to reduce vertical space, but I do put my opening braces on a new line because I find it easier to see the scope when the braces are lined up. The goal is readability, and sometimes that means using more vertical space, other times it means using less.
"I’ve never encountered this problem in real life": lucky you. Things like this don't just burn you, they give you 90% third degree burns (and that's just a few layers of management demanding a fix late in the evening).
@Richard I simply don’t buy that. As I’ve explained in the chat, even if this error should ever occur (which I find unlikely) it’s trivial to fix once you look at the stack trace because it’s obvious where the error is just by looking at the code. Your exaggerated claim is completely is completely baseless.
P
Peter Mortensen

The codebase I'm working on is scattered with code by people with a pathological aversion to braces, and for the people who come along later, it really can make a difference to maintainability.

The most frequent problematic example I have encountered is this:

if (really incredibly stupidly massively long statement that exceeds the width of the editor) do_foo;
    this_looks_like_a_then-statement_but_isn't;

So when I come along and wish to add a then-statement, I can easily end up with this if I'm not careful:

if (really incredibly stupidly massively long statement that exceeds the width of the editor) do_foo;
{
    this_looks_like_a_then-statement_but_isn't;
    i_want_this_to_be_a_then-statement_but_it's_not;
}

Given that it takes ~1 second to add braces and can save you at minimum a few confused minutes debugging, why would you ever not go with the reduced-ambiguity option? It seems like false economy to me.


Isn't the problem in this example in the improper indentation and too long lines rather than the braces?
Yes, but following design/coding guidelines which are only 'safe' assuming that people are also following other guidelines (such as not having too-long lines) seems to be asking for trouble. Had the braces been in from the start, it would be impossible to end up with an incorrect if-block in this situation.
How would adding braces (making it if(really long...editor){ do_foo;} help you avoid this case? Seems like the problem would still be the same. Personally I prefer to avoid braces when not necessary, however that has nothing to do with the time needed to write them but the reduced readability due to the two extra lines in the code.
Good point - I was assuming that enforcing use of braces would also result in them being put in a sensible place, but of course someone determined to make things difficult could put them in-line as in your example. I'd imagine most people would not, though.
The first and last thing I do when touching a file is hit the auto-format button. It eliminates most of these issues.
N
Nemanja Trifunovic

My 2c:

Use Indentation

Obviously

Never rely on operator precedence - Always use parentheses

I wouldn't use words "never and "always", but in general I see this rule being useful. In some languages (Lisp, Smalltalk) this is a non-issue.

Always use a { } block - even for a single line

I never do that and never had a single problem, but I can see how it can be good for students, esp. if they studied Python before.

Const object on left side of comparison

Yoda conditions? No, please. It hurts readability. Just use the maximum warning level when you compile your code.

Use unsigned for variables that are >= 0

OK. Funny enough, I've heard Stroustrup disagree.

Set Pointer to NULL after deletion - Double delete protection

Bad advice! Never have a pointer which points to a deleted or non-existing object.


+1 just for the last point alone. A raw pointer has no business owning memory anyway.
With regards to using unsigned: not only Stroustrup, but K&R (in C), Herb Sutter and (I think) Scott Meyers. In fact, I've never heard anyone who truly understood the rules of C++ argue for using unsigned.
@JamesKanze In fact, on the same occasion I heard Stroustrup's opinion (a Boston conference in 2008), Herb Sutter was there and disagreed with Bjarne on the spot.
Just to complete the "unsigned is broken", one of the problems is that when C++ compares similar sized signed and unsigned types, it converts to the unsigned one before doing the comparison. Which results in a change in value. Converting to the signed wouldn't necessarily be much better; the comparison should really take place "as if" both values were converted to a larger type which could represent all of the values in either type.
@SteveJessop I think you have to take it in the context of a function returning unsigned. I'm sure he has no problem with exp(double) returning a value more than MAX_INT:-). But once again, the real problem is implicit conversions. int i = exp( 1e6 ); is perfectly valid C++. Stroustrup actually proposed deprecating lossy implicit conversions at one point, but the committee wasn't interested. (An interesting question: would unsigned -> int be considered lossy. I'd consider both unsigned -> int and int -> unsigned lossy. Which would go a long way to making unsigned OK
P
Peter Mortensen

It is more intuitive and easily understandable. It makes the intent clear.

And it ensures that the code doesn't break when a new user might unknowingly miss the {, } while adding a new code statement.


Makes the intent clear +1, this is probably the most concise and accurate reason.
P
Peter Mortensen

To add to the very sensible suggestions in previous answers, one example I encountered while refactoring some code of where this becomes critical was as follows: I was altering a very large codebase to switch from one API to another. The first API had a call to set Company Id as follows:

setCompIds( const std::string& compId, const std::string& compSubId );

whereas the replacement needed two calls:

setCompId( const std::string& compId );
setCompSubId( const std::string& compSubId );

I set about changing this using regular expressions which was very successful. We also passed the code through astyle, which really made it very much more readable. Then, part way through the review process, I discovered that in some conditional circumstances it was changing this:

if ( condition )
   setCompIds( compId, compSubId );

To this:

if ( condition )
   setCompId( compId );
setCompSubId( compSubId );

which is clearly not what what was required. I had to go back to the beginning do this again by treating the replacement as completely within a block and then manually altering anything that ended up looking goofy (at least it wouldn't be incorrect).

I notice that astyle now has the option --add-brackets which allows you to add brackets where there are none and I strongly recommend this if you ever find yourself in the same position as I was.


I once saw some documentation that had the wonderful coinage "Microsoftligent". Yes, it's possible to make significant mistakes with global search and replace. That just means that global search and replace has to be used intelligently, not microsoftligently.
I know this isn't my post-mortem to perform, but if you're going to do text replacement on source code then you should do it according to the same rules you'd use for the kind of text replacement that's well-establised in the language: macros. You shouldn't write a macro #define FOO() func1(); \ func2(); (with a linebreak after the backslash), same goes for search and replace. That said, I have seen "always use braces" advanced as a style rule precisely because it saves you from wrapping all your multi-statement macros in do .. while(0). But I disagree.
Btw, that's "well-established" in the sense that Japanese knotweed is well-established: I'm not saying we should go out of our way to use macros and text-replacement, but I'm saying that when we do such a thing, we should do it in a way that works, rather than doing something that only works if a particular a style rule was succesfully imposed on the whole code base :-)
@SteveJessop One could also argue for braces and a belt. If you have to use such macros (and we did, before C++ and inline), then you should probably aim for them to work as much like a function as possible, using the do { ... } while(0) trick if necessary (and lots of extra parentheses. But that still wouldn't stop you from using braces everywhere, if that's the house style. (FWIW: I've worked in places with varying house styles, covering all of the styles discussed here. I've never found any to be a serious problem.)
And I reckon, the more styles you've worked with the more carefully you read and edit code. So even if you have a preference what's easiest to read, you'll still successfully read the others. I worked in a company where different components were written in different "house styles" by the different teams, and the correct solution is to complain about it in the lunch room to no great effect, not to try to create a global style :-)
L
Lukasz Madon

I am using {} everywhere except a few cases where it's obvious. Single line is one of the cases:

if(condition) return; // OK

if(condition) // 
   return;    // and this is not a one-liner 

It may hurt you when you add some method before return. Indentation indicates that return is executing when condition is met, but it will return always.

Other example in C# with using statment

using (D d = new D())  // OK
using (C c = new C(d))
{
    c.UseLimitedResource();
}

which is equivalent to

using (D d = new D())
{
    using (C c = new C(d))
    {
        c.UseLimitedResource();
    }
}

Just use commas in the using statement and you don't have to :)
@minitech That simply doesn’t work here – you can only use the comma when the types are equal, not for unequal types. Lukas’ way of doing this is the canonical way, the IDE even formats this differently (note the lack of automatic indentation of the second using).
K
KeithS

The most pertinent example I can think of:

if(someCondition)
   if(someOtherCondition)
      DoSomething();
else
   DoSomethingElse();

Which if will the else be paired with? Indentation implies that the outer if gets the else, but that's not actually how the compiler will see it; the inner if will get the else, and the outer if doesn't. You would have to know that (or see it behave that way in debugging mode) to figure out by inspection why this code might be failing your expectations. It gets more confusing if you know Python; in that case you know that indentation defines code blocks, so you would expect it to evaluate according to the indentation. C#, however, doesn't give a flying flip about whitespace.

Now, that said, I don't particularly agree with this "always use brackets" rule on its face. It makes code very vertically noisy, reducing the ability to read through it quickly. If the statement is:

if(someCondition)
   DoSomething();

... then it should be written just like this. The statement "always use brackets" sounds like "always surround mathematical operations with parentheses". That would turn the very simple statement a * b + c / d into ((a * b) + (c / d)), introducing the possibility of missing a close-paren (the bane of many a coder), and for what? The order of operations is well-known and well-enforced, so the parentheses are redundant. You'd only use parentheses to enforce a different order of operations than would normally be applied: a * (b+c) / d for instance. Block braces are similar; use them to define what you want to do in cases where it differs from the default, and is not "obvious" (subjective, but usually pretty common-sense).


@AlexBrown ...which was exactly my point. The rule as stated in the OP is "always use brackets, even for single lines", which I disagree with for the reason I stated. Brackets would help with the very first code example, because the code will not behave the way it's indented; you'd have to use brackets to pair the else with the first if instead of the second. Please remove the downvote.
K
Konrad Borowski

Because when you have two statements without {}, it's easy to miss an issue. Let's assume that the code looks like this.

int error = 0;
enum hash_type hash = SHA256;
struct hash_value *hash_result = hash_allocate();

if ((err = prepare_hash(hash, &hash_result))) != 0)
    goto fail;
if ((err = hash_update(&hash_result, &client_random)) != 0)
    goto fail;
if ((err = hash_update(&hash_result, &server_random)) != 0)
    goto fail;
if ((err = hash_update(&hash_result, &exchange_params)) != 0)
    goto fail;
    goto fail;
if ((err = hash_finish(hash)) != 0)
    goto fail;

error = do_important_stuff_with(hash);

fail:
hash_free(hash);
return error;

It looks fine. The issue with it is really easy to miss, especially when the function containing the code is way larger. The issue is that goto fail is ran unconditionally. You can easily imagine how frustrating this is (making you ask why last hash_update always fails, after all everything looks fine in hash_update function).

However, that doesn't mean I'm for adding {} everywhere (in my opinion, seeing {} everywhere is annoying). While it can cause issues, it never did for my own projects, as my personal coding style forbids conditionals without {} when they aren't on the same line (yes, I agree that my coding style is unconventional, but I like it, and I use project's code style when contributing to other projects). This makes the following code fine.

if (something) goto fail;

But not the following one.

if (something)
    goto fail;

Exactly. Just don't put the (completely unnecessary) newline + indent, and you completely sidestep this issue that everyone is always so quick to bring up.
D
Drona

It makes your code more readable by clearly defining the scope of your loops and conditional blocks. It also saves you from accidental mistakes.


T
Tom Tanner

wrt 6: It's safer because deleteing a null pointer is a no-op. So if you happen to accidentally go through that path twice, you won't cause memory corruption be freeing memory that is either free or has been allocated to something else.

This is most of an issue with static file scope objects and singletons that have not very clear lifetimes and have been known to get recreated after they've been destroyed.

In most cases, you can avoid the need for this by using auto_ptrs


If you happen to go through that path twice you've got a programming error. Setting a pointer to null to make this error less harmful doesn't solve the underlying problem.
Agreed, but I have seen this recommended before, and I believe it's in some professional programming standards. I was commenting more on why the poster's professor had come up with it, rather than when it was any good
Following up to what Pete Becker said: it doesn't solve the underlying problem, but it may mask it. (There are cases where you would set a pointer to NULL after deleting it. If NULL is a correct value for the pointer to have in those circumstances; e.g. the pointer points to a cached value, and NULL indicates an invalid cache. But when you see someone setting a pointer to NULL as the last line in a destructor, you wonder if he knows C++.)
P
Peter Mortensen

I like Luchian's accepted answer. In fact, I learned the hard way that he is right, so I do always use braces, even for single-line blocks. However, personally I make an exception when writing a filter, as you are in your example. This:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0)
    {
        j++;
    }
}

looks cluttered to me. It separates the 'for' loop and the 'if' statement into separate actions, when really your intent is a single action: to count all of the integers divisible by 2. In a more expressive language, this could be written something like:

j = [1..100].filter(_%2 == 0).Count

In languages which lack closures, the filter cannot be expressed in a single statement, but must be a for loop followed by an if statement. However, it is still one action in the mind of the programmer, and I believe that should be reflected in the code, like so:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
  if (i % 2 == 0)
{
    j++;
}

I like how everyone manages to ignore for (int i = 0; i < 100; i += 2);, for the sake of continuing the argument about indentation ;-) There's probably a whole separate bunfight we could have, how "best" to express the logic "for each i in a certain range with a certain property" in C++ without a loop, using some nightmare combination of standard algorithms, filter_iterator and/or counting_iterator.
Also, if we had that then we could disagree about how to indent the resulting massive single statement.
@Steve, It's just an example though. There are plenty of legitimate uses of the pattern. Obviously if you want to count the numbers from 1 to 100 which are divisible by 2, all you have to do is 100/2.
Sure, I know, that's why I abstracted to "for each i in a certain range with a certain property". It's just that usually on SO, people are very quick to ignore the actual question in favour of a completely different approach to the example given. But indenting is important, so we don't ;-)
P
Peter Mortensen

One option for helping to prevent the errors that have been described in previous answers is to inline what you want to happen when you don't use braces. It makes it much harder to not notice the errors when you try to modify the code.

if (condition) doSomething();
else doSomethingElse();

if (condition) doSomething();
    doSomething2(); // Looks pretty obviously wrong
else // doSomethingElse(); also looks pretty obviously wrong

The second option would yield a compilation error, because the else is not associated with an if.
One not so visible problem with inline is that most IDEs on default change it to the indented style when using their autoformat utility.
@Honza: that's a highly charged political issue, though. If we're co-operating on a code base, either we have to use the same indenting style down to every last detail, or we have to both agree not to autoformat existing code "just because". If the former then the agreed style could still include this, but you'd have to either configure your IDE to respect it or not use autoformat. Agreeing that the common format is "whatever my IDE autoformats to" is all very well if we all use the same IDE forever, not so good otherwise.
P
Peter Mortensen

Looking through the answers no one's explicitly stated the sort of practice I make a habit of, telling the story of your code:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0)
    {
        j++;
    }
}

Becomes:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0) j++;
}

Putting the j++ on the same line as the if should signal to anyone else, "I only want this block to ever increment j". Of course, this is only worthwhile if the line is as simplistic as possible, because putting a breakpoint here, as peri mentions, is not going to be very useful.

In fact, I've just run across part of the Twitter Storm API that has this 'sort' of code in Java. Here is the relevant snippet from the executed code, on page 43 of this slideshow:

...
Integer Count = counts.get(word);
if (Count=null) count=0;
count++
...

The for loop block has two things in it, so I wouldn't inline that code. I.e., never:

int j = 0;
for (int i = 0 ; i < 100 ; ++i) if (i % 2 == 0) j++;

It's awful and I don't even know if it works (as intended); don't do this. New lines and braces help distinguish separate, but related pieces of code, in the same way a comma or a semicolon do in prose. The above block is as bad a really long sentence with a few clauses and some other statements that never break or pause to distinguish separate parts.

If you really want to telegraph to someone else it's a one-line only job, use a ternary operator or ?: form:

for (int i = 0 ; i < 100 ; ++i) (i%2 ? 0 : >0) j++;

But this is verging on code golf, and I think it is not great practice (it's not clear to me if I should put the j++ on one side of the : or not). NB I've not run a ternary operator in C++ before, and I don't know if this works, but it does exist.

In short:

Imagine how your reader (i.e., the person maintaining the code) interprets your story (code). Make it as clear for them as possible. If you know the novice coder/student is maintaining this, perhaps even leave in as many {} as possible, just so they don't get confused.


(1) Putting the statement on the same line makes it less readable, not more. Especially simple thinks like an increment are easily overlooked. Do put them on a new line. (2) Of course you can put your for loop on a single line, why shouldn’t this work? It works for the same reason that you can omit the braces; newline is simply not significant in C++. (3) Your conditional operator example, besides being horrible, is invalid C++.
@KonradRudolph thanks, I'm a bit rusty at C++. I never said (1) was more readable, but it would signal to be that that piece of code was meant to be online one line. (2) My comment was more that I wouldn't be able to read it and know it worked, whethert at all or as intended; it's an example of what not to do for this reason. (3) Thanks, I've not written C++ in a long time. I'll fix that now.
Also putting more then one expression in one line makes it harder to debug code. How do you put breakpoint on 2nd expresion in that line?
P
P.P

If you are a compiler, it doesn't make any difference. Both are the same.

But for programmers, the first one is more clear, easy to read and less error-prone.


Other than opening { on it's own line, anyway.
P
Peter Mortensen

Another example of adding curly braces.

Once I was searching for a bug and found such code:

void SomeSimpleEventHandler()
{
    SomeStatementAtTheBeginningNumber1;
    if (conditionX) SomeRegularStatement;
    SomeStatementAtTheBeginningNumber2;
    SomeStatementAtTheBeginningNumber3;
    if (!SomeConditionIsMet()) return;
    OtherwiseSomeAdditionalStatement1;
    OtherwiseSomeAdditionalStatement2;
    OtherwiseSomeAdditionalStatement3;
}

If you read the method line-by-line you will notice that there is a condition in the method that returns if it's not true. But actually it looks like 100 other simple event handlers that set some variables based on some conditions. And one day the Fast Coder comes in and adds additional variable setting statements at the end of the method:

{
    ...
    OtherwiseSomeAdditionalStatement3;
    SetAnotherVariableUnconditionally;
}

As a result, the SetAnotherVariableUnconditionnally is executed when the SomeConditionIsMet(), but the fast guy didn't notice it because all lines are almost similar in size and even when the return condition is vertically indented it is not-so noticeable.

If the conditional return is formatted like this:

if (!SomeConditionIsMet())
{
    return;
}

it is much noticeable and the Fast Coder will find it at a glance.


If your fast coder cannot be bothered to spot a syntax-highlighted return statement within the body of a function before adding something to it, you shouldn't let the fast coder get near your code. You won't stop such a guy from trolling around your code by including braces.
@cmaster He doesn't work with us anymore. Anyway, syntax highlighting is good, but remember that there are persons that do not see clearly (I saw even a post from a blind programmer last year).
P
Peter Mortensen

I consider the first one to be clearer than the second. It gives the feeling of closing instructions. With short code it is fine, but when code gets complex, {...} helps a lot, even if it is endif or begin...end.

// First
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0)
    {
        j++;
    }
}


// Second
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
i++;

J
John

It is best to set the pointer to NULL when you have finished with it.

Here is an example why:

Class A does the following:

Allocates a block of memory Then some time later, it delete this block of memory but does not set the pointer to NULL

Class B does the following

Allocates memory (and in this instance it happens to be given the same memory block that was deleted by class A.)

At this point both Class A and Class B have pointers pointing to the same memory block, as far as Class A is concerned this block of memory does not exists because it is finished with it.

Consider the following problem:

What if there was a logic error in Class A which resulted in it writing to memory that now belongs to Class B?

In this particular instance, you will not get an bad access exception error because the memory address is legal, all the while class A is now effectively corrupting class B data.

Class B may eventually crash if it encounters unexpected values and when it does crash, chances are, you will spend quite a long time hunting this bug in class B when the problem is in class A.

If you had set the deleted memory pointer to NULL, you would have gotten an exception error as soon as any logic errors in Class A tried to write to NULL pointer.

If you are worried about the logic error with double delete when pointers are NULL for the second time, then add assert for this.

Also: If you are going to down vote, please explain.


If there was a logic error, it should be fixed, rather that masking it.
@Barmar, OP says... 6. Set Pointer to NULL after deletion - Double delete protection // not bad. Some people have responded on not setting it to Null and I am saying why it should be set to NULL, what part of 6. my answer to setting NULL doesn't fit in 6?
@Shaquin, And how do you propose in finding these logic errors in the first place? Once you set the pointer variable to NULL after memory has been deleted. Any attempt to reference NULL pointer will crash to the debugger on the line your illegal attempt was made. You can trace back and see where the logic error was and fix the problem. If you do not set the pointer variable to NULL after you have deleted the memory, your illegal attempt to write this deleted memory due to UNAWARE logic errors may succeed and therefore does not crash at that point. It is not masking it.
s
supercat

There are a number of possible ways of writing control statements; certain combinations of them may co-exist without impairing legibility, but other combinations will cause trouble. The style

if (condition)
  statement;

will co-exist comfortably with some of the other ways of writing control statements, but not so well with others. If multi-line controlled statements are written as:

if (condition)
{
  statement;
  statement;
}

then it will be visually obvious which if statements control a single line and which ones control multiple lines. If, however, multi-line if statements are written as:

if (condition) {
  statement;
  statement;
}

then the likelihood of someone trying to extend a single-statement if constructs without adding the necessary braces may be much higher.

The single-statement-on-next line if statement may also be problematic if the codebase makes significant use of the form

if (condition) statement;

My own preference is that having the statement on its own line generally enhances legibility except in cases where there are many if statements with similar control blocks, e.g.

if (x1 > xmax) x1 = xmax;
if (x1 < xmin) x1 = xmin;
if (x2 > xmax) x2 = xmax;
if (x2 < xmin) x2 = xmin;
etc.

in which case I will generally precede and follow such groups of if statements with a blank line to visually separate them from other code. Having a range of statements that all start with if at the same indentation will then provide a clear visual indication that there's something unusual.


M
Michiel Cornille

After 10 years of being in camp "always use braces" I recently switched to not using them as much anymore. Mostly inspired by some of Uncle Bob's arguments around how to write clean code I now believe that it is more readable to write them without the braces.

if(guardClause)
      throw new SomeException(..)

Uncle Bob argues that writing more than one line of code inside an if/for statement is a potential readability smell.

e.g.

if(someCondition)
{
   doTechnicalThingX();
   doTechnicalThingY();
   doTechnicalThingZ();
}

Should probably be refactored as

if(someCondition)
    doFunctionalThingA();

Somehow for me it helps not putting the braces there because I get the reminder that I'm writing too much code inside the if block.

I do believe that code style is a team decision as others have mentioned.


I agree...most of my conditionals and loops are one liners. But current best practices where I work require braces..so I have to follow their convention. I have been programming over 25 years and I am not sure when this became a big deal to people. 90% of the time if you auto format your code then this is not an issue. Other 10% of accidents caused by braces I just am very good at spotting. Lots of coders are pretty passionate about this rule so if your shop says its best practice you need to follow their best practices.
P
Peter Mortensen

I have to admit that I do not always use {} for single lines, but it's a good practise.

Let’s say you write code without brackets that looks like this: for (int i = 0; i < 100; ++i) for (int j = 0; j < 100; ++j) DoSingleStuff();

And after some time you want to add some other stuff in the j loop, and you just do that by alignment and forget to add brackets.

Memory deallocation is faster. Let’s say you have a big scope and create big arrays inside (without new so they are on the stack). Those arrays are removed from memory just after you leave the scope. But it is possible that you use that array in one place and it will be on the stack for a while and be some kind of rubbish. As a stack have limited and quite small size, it is possible to exceed the stack size. So in some cases it is better to write {} to preventing that. Note that this is not for a single line, but for such situations: if (...) { //SomeStuff... {//we have no if, while, etc. //SomeOtherStuff } //SomeMoreStuff }

The third way to use is similar to the second. It is just not to make the stack cleaner, but to open some functions. If you use mutex in long functions usually it is better to lock and unlock just before accessing data and just after finishing reading/writing that. Note: This way is used if you have some of your own class or struct with a constructor and destructor to lock memory.

What is more: if (...) if (...) SomeStuff(); else SomeOtherStuff(); // Goes to the second if, but alignment shows it is on first...

All in all, I cannot say, what the best way to always use {} is for a single line, but it is nothing bad to do that.

If you write compiling code brackets for a single line does nothing, but if your code will be interpreted it slows the code very very slightly. Very slightly.


Ö
Öö Tiib

Always having curly braces is a very simple and robust rule. However, the code may look inelegant when there are a lot of braces.

If the rules allow to omit curly braces then there should be more detailed style rules and more sophisticated tools. Otherwise it may easily result in chaotic and confusing (not elegant) code.

Therefore looking at a single style rule separate from the rest of the style guides and tools used is likely fruitless. I will just bring some important details about that rule #3 that haven't even been mentioned in other answers.

The first interesting detail is that most proponents of that rule agree to violate it in the case of else. In other words, they do not want it to result with such code:

// Pedantic rule #3
if ( command == Eat )
{
    eat();
}
else
{
    if ( command == Sleep )
    {
        sleep();
    }
    else
    {
        if ( command == Drink )
        {
            drink();
        }
        else
        {
            complain_about_unknown_command();
        }
    }
}

Instead, if they see it they may even suggest to write it like this:

// Not fully conforming to rule #3
if ( command == Eat )
{
    eat();
}
else if ( command == Sleep )
{
    sleep();
}
else if ( command == Drink )
{
    drink();
}
else
{
   complain_about_unknown_command();
}

That is technically a violation of rule #3 since there are no curly brackets between else and if but majority consider it more obvious and easy to read. Such duality of the rule surfaces when trying to apply it to a code base automatically with a mindless tool. Indeed, why argue? Just let a tool to apply the style automatically.

The second detail (that is also often forgotten by proponents of that rule) is that the illusion errors that may happen are never only because of violations of that rule #3. Actually, those almost always involve violations of rule #1 too (that no one argues with). Again from the viewpoint of automatic tools, it is not hard to make a tool that immediately complains (or even fixes) when rule #1 is violated and so most of the errors can be caught timely.

The third detail (that is often forgotten by opponents of that rule) is the confusing nature of an empty statement that is represented by a single semicolon. Most developers with some experience became confused sooner or later by a sole misplaced semicolon or by an empty statement that is written using a sole semicolon. Two curly braces instead of a single semicolon are visually way easier to spot.

So TL;DR my suggestion is instead of agreeing such rules agree on configuration of auto-formatting tools and make these a part of build process. The tools are often smarter than participants of such argument.