Phlash6
Phlash6

Reputation: 149

If statements without brackets

I'm hoping to get some clarification on if and if else statements that do not have brackets and how to read them. I can read if else, and else if statements with brackets easily and they make sense to me but these have always confused me, here is a sample question.

if (x > 10)      
     if (x > 20)
          printf("YAY\n");    
else      printf("TEST\n");

Upvotes: 12

Views: 47703

Answers (3)

Mureinik
Mureinik

Reputation: 311188

Without the brackets, the else will relate to the if it's immediately after. So, to properly indent your example:

if (x > 10)      
     if (x > 20)
          printf("YAY\n"); 
     else // i.e., x > 10 but not x > 20
          printf("TEST\n");

Upvotes: 10

Hatted Rooster
Hatted Rooster

Reputation: 36483

An if statement without brackets will only take into account the next expression after the if:

 if(foo > 5)
   foo = 10;
 bar = 5;

Here, foo will only be set to 10 if foo is bigger than 5 but bar will always be set to 5 because it's not inside the scope of the if statement, that would require brackets.

Upvotes: 3

Victor Johnson
Victor Johnson

Reputation: 456

If there are no brackets on an if/else, the first statement after the if will get executed.

If statement:

if (condition)
    printf("this line will get executed if condition is true");
printf("this line will always get executed");

If/else:

if (condition)
    printf("this line will get executed if condition is true");
else
    printf("this line will get executed if condition is false");
printf("this line will always get executed");

Note: Your code will break if there are multiple commands between an if and its matching else.

if (condition)
    printf("this line will get executed if condition is true");
    printf("this line will always get executed");
else
    printf("this else will break since there is no longer a matching if statement");

Upvotes: 17

Related Questions