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");
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.
In C, C++ and Java, if you add another statement to the then clause of an if-then: if (condition) statement1();
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With