if statement
From cppreference.com
C
Concurrency support (C11)
Statements
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.
[edit] Syntax
attr-spec-seq (optional)
if (
expression )
statement-true
(1)
attr-spec-seq (optional)
if (
expression )
statement-true else
statement-false
(2)
expression
-
an expression of any scalar type
statement-true
-
any statement (often a compound statement), which is executed if expression compares not equal to 0
statement-false
-
any statement (often a compound statement), which is executed if expression compares equal to 0
[edit] Explanation
expression must be an expression of any scalar type.
If expression compares not equal to the integer zero, statement-true is executed.
In the form (2), if expression 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 == 1 return b; // b == 0 in C89, b == 1 in C99 }
[edit] Notes
The else is always associated with the closest preceding if (in other words, if statement-true is also an if statement, then that inner if statement must contain an else part as well):
If statement-true is entered through a goto, statement-false is not executed.
[edit] Keywords
[edit] Example
Run this code
Output:
i > 2 is false i == 3 i != 3 is false
[edit] References
- C23 standard (ISO/IEC 9899:2024):
- 6.8.5.2 The if statement (p: 154)
- C17 standard (ISO/IEC 9899:2018):
- 6.8.4.1 The if statement (p: 108-109)
- C11 standard (ISO/IEC 9899:2011):
- 6.8.4.1 The if statement (p: 148-149)
- C99 standard (ISO/IEC 9899:1999):
- 6.8.4.1 The if statement (p: 133-134)
- C89/C90 standard (ISO/IEC 9899:1990):
- 3.6.4.1 The if statement
[edit] See also
C++ documentation for if statement