“if” statement syntax differences between C and C++

This is a subtle and important difference between C and C++. In C++ any statement may be a declaration-statement. In C, there is no such thing as a declaration-statement; instead, a declaration can appear instead of a statement within any compound-statement.

From the C grammar (C17 spec):

compound-statement: “{” block-item-listopt “}”
block-item-list: block-item | block-item-list block-item
block-item: declaration | statement

From the C++ grammar (C++14 spec):

compound-statement:
“{” statement-seqopt “}”
statement-seq:
statement |
statement-seq statement
statement: … | declaration-statement | …

It is not clear why this difference exists, it is just the way the languages evolved. The C++ syntax dates all the way back to (at least) C++85. The C syntax was introduced sometime between C89 and C99 (in C89, declarations had to be at the beginning of a block)


In the original 85 and 89 versions of C++, the scope of a variable defined in a declaration-statement was “until the end of the enclosing block“). So a declaration in an if like this would not immediately go out of scope (as it does in more recent versions) and instead would be in scope for statements following the if in the same block scope. This could lead to problems with accessing uninitialized data when the condition is false. Worse, if the var had a non-trivial destructor, that would be called when the scope ended, even if it had never been initialized! I suspect trying to avoid these kinds of problems is what led to C adopting a different syntax.

Leave a Comment

deneme bonusudeneme bonusu veren sitelerOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino