Declarations within an if statement

Viewed 57

Are declarations within an if statement illegal without an enclosing brace? For example:

if (argc == 2)
    char* str = "Two";
else
    char* str = "Not two";

Would need to be converted to:

if (argc == 2) {
    char* str = "Two";
} else {
    char* str = "Not two";
}

Out of curiosity, why is this so? I understand the need for braces with multiple statements such as:

if (something)
    printf(something);
    printf(something);

Where the above really "means" the following in lieu of explicit braeces:

if (something) {
    printf(something);
}
printf(something);

But why is a single statement/declaration allowed, if it includes only a single ;?

1 Answers

The syntax of an if statement (with an else clause) is:

if (expression) statement else statement

And this:

char* str = "Two";

Is not a statement but a declaration, therefore it's not valid in your first code snippet.

The second snippet with curly braces works because the braces denote a compound statement, and a compound statement may contain both statements and declarations within it.

Note however that even in the second case which compiles, the variable str defined in each sub-block goes out of scope once the if statement completes and cannot be referenced. What you probably want is:

char *str;
if (argc == 2) {
    str = "Two";
} else {
    str = "Not two";
}

Or equivalently:

char *str;
if (argc == 2)
    str = "Two";
else
    str = "Not two";
Related