An if statement has three parts: the keyword if, a condition in parentheses, and a body that runs only when the condition is true. The simplest form puts one statement after the condition:
if (temperature > 30)
std::cout << "Hot day\n";
To run more than one statement, wrap them in braces. The braces form a block, and a block counts as a single statement:
if (temperature > 30) {
std::cout << "Hot day\n";
std::cout << "Bring extra water\n";
}
The parts of the syntax
- The keyword. It is
if, in lowercase. C++ is case-sensitive, soIfdoes not work. - The parentheses. They are required around the condition.
if temperature > 30does not compile. - The condition. It can be any expression that converts to
bool. A non-zero number counts as true and zero counts as false. Most conditions use c comparison operators such as==and<. - The body. It is either one statement ending in a semicolon or a block in braces.
- The optional else part. An
elsecan follow the body. The rules for that part are covered in if else statement syntax in c.
A complete example
#include <iostream>
int main() {
int temperature = 33;
if (temperature > 30) {
std::cout << "Hot day\n";
std::cout << "Bring extra water\n";
}
std::cout << "Done\n";
return 0;
}
With temperature set to 33, the output is:
Hot day
Bring extra water
Done
If you set temperature to 20, the two lines in the block are skipped and only Done is printed. The last line sits outside the block, so it runs either way.
The empty-body trap
A semicolon placed right after the condition ends the if statement with an empty body:
int x = -3;
if (x > 0);
std::cout << "x is positive\n";
The indented line is not part of the if, so it runs every time. This program prints x is positive even though x is negative. Many compilers can warn about a stray semicolon like this when extra warning flags are turned on.
Declaring a variable in the condition
C++17 added a form that declares a variable before the condition, separated by a semicolon:
#include <iostream>
int main() {
int number = 42;
if (int remainder = number % 10; remainder == 0) {
std::cout << "Ends in 0\n";
} else {
std::cout << "Remainder is " << remainder << "\n";
}
return 0;
}
The output is Remainder is 2. The variable remainder is visible in both branches, but it does not exist after the if statement ends. This form needs C++17 or a later standard, and C does not have it.
Key points
- The keyword is
if, the condition goes in parentheses, and the body runs only when the condition is true. - A body is either one statement ending in a semicolon or a block in braces.
- Do not put a semicolon right after the closing parenthesis unless you want an empty body.
- In C++17 and later, a variable declared in the condition is scoped to the
ifand itselse.