if Conditional selection statement
if Conditional selection statement
if runs one statement when a scalar condition is nonzero. Braces group code; else and else if handle alternatives. Use ==, not =; parentheses are required.
| Category | Control flow |
|---|---|
| Kind | Keyword / Statement |
| C standard | C89 / C90 |
📝 Syntax
if (expr) statement; else statement;
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
positive
🏷️ Related control-flow keywords
📚 Related Tutorials
❓ FAQ
QMust an if condition be written as a comparison?
ANo. Any scalar expression can be a condition: zero is false and nonzero is true. Pointers can be compared with a null pointer constant and integers can be tested directly, although an explicit comparison is often clearer.
QWhy doesn't if (x = 1) test whether x equals 1?
A= is assignment, so the expression first writes 1 to x and then uses the assignment result, 1, as a true condition. Use == for equality; compiler warnings can catch many accidental assignments.
QHow many statements does if control without braces?
AIt directly controls only the single statement immediately following it. Later statements run regardless of indentation. Use a compound statement, { ... }, to control multiple statements.