Why do I need curly braces?

Consider this simple program.

$ cat fails.c #include <stdio.h> int main(){ int i = 10; if (i == 10) int j = 11; return 0; } 

This fails to compile by indicating this error:

 $ gcc fails.c fails.c: In function 'main': fails.c:7:3: error: expected expression before 'int' int j = 11; ^ 

But this goes very well:

 #include <stdio.h> int main(){ int i = 10; if (i == 10){ int j = 11; } return 0; } 

I realized that working around is putting those {} . But I want to know why this is required.

Why does it behave this way when something like printf acceptable?

 #include <stdio.h> int main(){ int i = 10; if (i == 10) printf("some text\n"); return 0; } 
+7
c
source share
2 answers

This is because the if should be followed by:

C99 / 6.8.4

if (expression) statement

However, the announcement is not :

C99 / 6.8

statement:

labeled operator

compound operator

operator expression

Operator selection

iteration operator

jumping operator

When placed inside {} , this is a compound statement, so ok.

+5
source share

There is a distinction between declaration and expression.

 int j = 11; 

is an announcement. An if followed by a statement. Putting {} after the if statement results in a compound statement. A compound statement cannot have any other statement in it, or it can have an declaration.

+1
source share

All Articles