Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I need the curly braces here?

Tags:

c

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;
}
like image 310
struggling_learner Avatar asked Mar 21 '18 18:03

struggling_learner


1 Answers

This is because if must be followed by a statement:

C99/6.8.4

if ( expression ) statement

However, a declaration is not a statement:

C99/6.8

statement:

labeled-statement

compound-statement

expression-statement

selection-statement

iteration-statement

jump-statement

When put inside a {}, it is a compound-statement, thus ok.

like image 81
llllllllll Avatar answered Oct 12 '22 13:10

llllllllll