| Labels | ||||
| Expression statements | ||||
| Compound statements | ||||
| Selection statements | ||||
if | ||||
| Iteration statements | ||||
| Jump statements | ||||
Conditionally executes code.
Used where code needs to be executed only if some condition is true.
Contents |
attr-spec-seq (optional)if (expression)statement-true | (1) | ||||||||
attr-spec-seq (optional)if (expression)statement-trueelsestatement-false | (2) | ||||||||
| attr-spec-seq | - | (C23) an optional list ofattributes, applied to theif statement |
| expression | - | anexpression of any scalar type |
| statement-true | - | anystatement (often a compound statement), which is executed ifexpression compares not equal to0 |
| statement-false | - | anystatement (often a compound statement), which is executed ifexpression compares equal to0 |
expression must be an expression of anyscalar type.
Ifexpression compares not equal to the integer zero,statement-true is executed.
In the form(2), ifexpression compares equal to the integer zero,statement-false is executed.
As with all other selection and iteration statements, the entire if-statement has its own block scope: enum{a, b}; int different(void){if(sizeof(enum{b, a})!=sizeof(int))return a;// a == 1return b;// b == 0 in C89, b == 1 in C99} | (since C99) |
Theelse is always associated with the closest precedingif (in other words, ifstatement-true is also anif statement, then that innerif statement must contain anelse part as well):
Ifstatement-true is entered through agoto,statement-false is not executed.
Output:
i > 2 is falsei == 3i != 3 is false
C++ documentation forif statement |