wolf_adventures1909 wolf_adventures1909 - 3 months ago 8
C++ Question

C++: should you use {} brackets with if statements

My question is which of the following is best to use in C++:

if (...) {
// then...
}


or:

if (...)
// then


Both work, as far as I can tell, and I've seen references to both. So which is considered better style? Is it a per-programmer basis, or does it affect compilation, or anything else?

Thanks!

Answer

Of course, this depends on the programmer. But I would recommend you to use the first one.

if (...) {
    // then...
}

The second one is prone to errors.

if (...)
    // then

Say if you want to add another line to that,

if (...)
    // then
    // then line 2

Line 2 doesn't belong to the if block!

But if you had used the braces in the first place, this is not the case.