The if statement syntax
What you'll learn: How to use the if keyword to make your program execute specific code only when a certain condition is true.
Decisions in code
Up until now, your code has likely run like a simple recipe: do step A, then step B, then step C. But real-world logic requires branches. Think of a train track with a switch: if the switch is set to "Left," the train goes one way; otherwise, it keeps going straight. In C, the if statement is that switch. It allows your program to ask a question and only execute a block of code if the answer is "Yes" (True).
The basic structure
The syntax for an if statement is strict but logical. You use the keyword if, followed by a condition wrapped in parentheses (). Immediately after, you provide a block of code wrapped in curly braces {}.
#include <stdio.h>
int main() {
int age = 20;
// The condition (age >= 18) is checked
if (age >= 18) {
// This code only runs if the condition is true
printf("You are eligible to vote!\n");
}
return 0;
}
How it works
- The Condition: Inside the parentheses, you put a comparison. In the example above, we check if
ageis greater than or equal to 18. - ** The Gatekeeper:** If the condition is true, C enters the curly braces and runs every line of code inside them.
- The Skip: If the condition is false (for example, if
agewas 15), C completely ignores everything inside the curly braces and jumps straight to the next line of code after the closing brace}.
Pro-tip: Indentation
You’ll notice the code inside the {} is indented (pushed to the right). While C doesn't technically require this to run, humans do! Indentation makes it visually obvious which lines of code are "guarded" by the if statement.
Key takeaway
Use if (condition) { ... } to create a gated block of code that only runs when your condition evaluates to true.