If with and without curly braces

c, c++

Solution

Concerning run-time speed, they are exactly the same thing.

The C++11 Standard defines the first form to be an implicit variation of the second form. Per Paragraph 6.4/1, in fact:

[...] The substatement in a selection-statement (each substatement, in the `else` form of the `if` statement) implicitly defines a block scope (3.3). If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement. [Example:

if (x)
    int i;

can be equivalently rewritten as

if (x) {
    int i;
}

Thus after the if statement, i is no longer in scope. —end example ]

The additional compilation time required to parse the extra braces is so small that it can be safely disregarded. Choose the form which makes the code easier to read or to maintain in your case.

Problem

I read a question about `if` statement Which code is faster/same? if(a==1) return 0; if(a==1) { return 0; } Is there really any difference for speed or for compiler in this case? Thank you in advance.

Original source