Welcome to this tutorial on C++17 if/switch with Initializer! This lesson is designed for both beginners and intermediates who wish to expand their C++ programming knowledge. We'll delve deep into the new features of C++17, focusing on the if and switch statements, and learn how to use their initializer forms for improved coding efficiency.
Let's get started!
The if statement is a decision-making construct that checks a condition and executes the corresponding code if the condition is true.
if (condition) {
// Code executed if condition is true
}Pro Tip: The if statement can also be used with an else clause to execute different code when the condition is false.
if (condition) {
// Code executed if condition is true
} else {
// Code executed if condition is false
}C++17 introduced the if initializer as a way to initialize a variable based on a condition. This can make your code cleaner and more concise.
int x = 0;
if (someCondition) {
x = 10;
}
// Here, x will hold the value 0 or 10 depending on the conditionIn the above example, x is initialized with 0 and then reassigned the value 10 if the condition is true.
The switch statement is another decision-making construct that compares the value of an expression against a list of case labels.
switch (expression) {
case label1:
// Code executed if expression matches label1
break;
case label2:
// Code executed if expression matches label2
break;
// ...
default:
// Code executed if none of the labels match
}Pro Tip: Don't forget to include a break statement after each case block to prevent fall-through behavior.
Similar to if, C++17 also introduced the switch initializer form, which lets you initialize a variable within the switch statement.
int x;
switch (someExpression) {
case value1:
x = 10;
break;
case value2:
x = 20;
break;
// ...
}
// Here, x will hold the value 10 or 20 depending on the expressionIn the above example, x is initialized as an uninitialized int and then assigned the value 10 or 20 based on the someExpression.
#include <iostream>
int main() {
int number = 0;
if (number % 2 == 0) {
std::cout << "Number is even.\n";
number *= 2;
} else {
std::cout << "Number is odd.\n";
number++;
}
std::cout << "New number: " << number << '\n';
return 0;
}#include <iostream>
int main() {
int choice;
std::cout << "Enter your choice (1, 2, or 3): ";
std::cin >> choice;
int result;
switch (choice) {
case 1:
result = 10;
break;
case 2:
result = 20;
break;
case 3:
result = 30;
break;
default:
result = -1;
std::cout << "Invalid choice.\n";
}
std::cout << "Result: " << result << '\n';
return 0;
}What will the output be for the `if` initializer example when the input number is `5`?
What will the output be for the `switch` initializer example when the input choice is `3`?