Compound Statement
Sometimes we might need to execute several statements inside an if
statement. The following code won't do what you might expect (run it!)
#include <stdio.h>
int main() {
if (7 < 5)
printf("this cannot be true\n");
printf("no, this cannot be true\n");
return 0;
}
The reason for this is that C does not care about the indentation – that is, about those extra spaces we add to make the code readable. Only the first printf
is "within" the if
branch, the second is out. To tell the C compiler that both must be within the if
, we use curly braces to make a compound statement:
#include <stdio.h>
int main() {
if (7 < 5) {
printf("this cannot be true\n");
printf("no, this cannot be true\n");
} /* no semicolon needed */
return 0;
}
Note: you don't need to put a semicolon after the closing brace }
of a compound statement. If you do, the semicolon will be considered a separate empty statement, which most likely is not what you need.
So, if your if
branches need to have multiple statements, use { }
:
if (condition) {
statement;
statement;
statement;
} else {
statement;
statement;
}
I recommend to use { }
always, even if you only have just one statement inside the branch.