if, if ... else
suggest changeif and else:
An if statement checks whether a condition is true and then acts on that result:
if (condition) statement
The condition can be any valid C++ expression that is contextually converted to bool:
if (true) { /* code here */ } // evaluate that true is true and execute the code in the brackets
if (false) { /* code here */ } // always skip the code since false is always false
The condition can be a function call, a variable, or a comparison:
if (istrue()) { } // evaluate the function, if it returns true, the if will execute the code
if (isTrue(var)) { } // evaluate the return of the function after passing the argument var
if (a == b) { } // this will evaluate the return of the expression (a==b) which will be true if equal and false if unequal
if (a) { } // a bool is tested directly; for an integer, any non-zero value is true
To test more than one condition, you can do it in two ways:
using binary operators:
if (a && b) { } // True only if both a and b are true.
if (a || b) { } // true if a is true, b is true, or both are
using if / else if / else:
For a choice between two branches:
if (a == "test") {
// runs when a compares equal to "test"
} else {
// runs only when the first condition was false
}
For multiple choices:
if (a == 'a') {
// if a is a char valued 'a'
} else if (a == 'b') {
// if a is a char valued 'b'
} else if (a == 'c') {
// if a is a char valued 'c'
} else {
// a is none of the above
}
When every condition tests the same scalar value, a switch statement can express that choice. switch does not compare string contents.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents