Reputation: 1258
Consider this simple program:
fails.c
:
#include <stdio.h>
int main(){
int i = 10;
if (i == 10)
int j = 11;
return 0;
}
That fails to compile (gcc fails.c
), giving this error:
fails.c: In function ‘main’:
fails.c:7:3: error: expected expression before ‘int’
int j = 11;
^
But this one goes through just fine:
#include <stdio.h>
int main(){
int i = 10;
if (i == 10){
int j = 11;
}
return 0;
}
I figured that the work around, is to put those {}
in. But I wish to know why this is required.
Why does it behave this way, when something like printf
is acceptable?
#include <stdio.h>
int main(){
int i = 10;
if (i == 10)
printf("some text\n");
return 0;
}
Upvotes: 12
Views: 149
Reputation: 5369
It seems you compile your ANSI C code with C89 standard. And, unlike his successor C99, it requires all variables to be declared at the beginning of the scope. So, having int j = 11;
somewhere in-between other statements just contradicts that C89 rule. If you open a new scope just before that int j = 11;
, it's back to OK.
Actual reason of such C89 limitation should be an attempt to simplify memory management for stack-allocable variables. For instance, compare it with Pascal language that requires all variables to be declared in the special var
section before the code (so, it's even more strict that C89).
Upvotes: 0
Reputation: 105992
There is a difference between declaration and statement.
int j = 11;
is a declaration. if
statement shall be followed by a statement. Putting {}
after if
statement results in a compound statement. A compound statement can have no other statement in it or can have a declaration.
Upvotes: 1
Reputation: 16404
This is because if
must be followed by a statement:
if ( expression ) statement
However, a declaration is not a statement:
statement:
labeled-statement
compound-statement
expression-statement
selection-statement
iteration-statement
jump-statement
When put inside a {}
, it is a compound-statement, thus ok.
Upvotes: 8