Up until now, any code written here runs and then exits, it does not have abilitiy to make decisions. The if statement changes that...
if (condition_is_met)
{
}
The condition can be any logical expression or comparison.
else
You can also add an else
statement that runs if the condition is not met...
if (condition_is_met)
else
- Note
- In many cases, else statements can be simply omitted.
else if
These are great for simple tests, but what if you want to check multiple conditions and run different actions based on those? The answer is the "else if" statement...
if (condition)
{
}
else if (another_condition)
else if (yet_another_condition)
{
}
else
switch
The switch statement is a shorthand version of the if... else if... else statement. However, it does have a handicap.
switch (variable) {
case value:
break;
case another_value:
break;
case yet_another_value:
break;
case value1:
case value2:
case value3:
break;
default:
break;
}
A switch statement is simply shorthand for some else-if statements. In fact, you can attain the same behavior in an else-if statement.
if (variable == value)
else if (variable == value)
else if (variable == value)
else if (variable == value || variable == value || variable == value)
{
}
else
Example
The following code is a real-life(ish) example of when you would use an if statement... It also demonstrates nesting (putting one if statement inside another). You can copy and paste this code into your IDE and it will run...
#include <iostream>
using namespace std;
int main() {
char UsrInput;
cout << "Please enter an ASCII character: ";
cin >> UsrInput;
cout << endl;
if ((UsrInput >= 'A' && UsrInput <= 'Z') ||
(UsrInput >= 'a' && UsrInput <= 'z'))
{
cout << "The character you entered is a letter." << endl;
if (UsrInput >= 'A' && UsrInput <= 'Z')
cout << "The letter you entered is a UPPERCASE."
<< endl;
else cout << "The letter you entered is lowercase." << endl;
switch (UsrInput)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
cout << "The letter you entered is a vowel."
<< endl;
break;
default:
cout << "The letter you entered is NOT a vowel." << endl;
break;
}
}
else cout << "The character you entered is NOT a letter.";
}
assert
Assert statements will stop your code immediately if the given condition is met. Their primary use is debugging (checking for problems). Assert can be very useful for finding invalid values.
#include <cassert>
using namespace std;
int main() {
int input;
cin >> input;
assert(input < -100);
}
- Note
- When the code is deployed, you don't usually want to leave assert statements enabled. You can put the line
#define NDEBUG
anywhere above the #include <cassert>
line and all of the assertions in that file will be disabled.