Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statements without brackets

Tags:

c

if-statement

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");
like image 933
Phlash6 Avatar asked Feb 19 '15 17:02

Phlash6


People also ask

Can we use if statement without brackets?

Yes it is not necessary to use curly braces after conditions and loops (functions always need them) IF and only if there is just one statement following. In this case it automatically uses the next statement.

Do you need brackets for IF statement in C?

In C, C++ and Java, if you add another statement to the then clause of an if-then: if (condition) statement1();

What happens in a IF statement where there is no curly braces?

In C# curly braces are optional, but only for the first line of code. Meaning that if the statement does not have braces, only the line of code right after the if condition (the statement body) will be executed. Everything else falls outside the statement body and therefore will not be executed. Save this answer.

Do you need braces in if statement Java?

Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.


1 Answers

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");
like image 157
Victor Johnson Avatar answered Sep 26 '22 00:09

Victor Johnson