Video Coming Soon...
13: switch-statements
This exercise is pending. Quick notes about this exercise:
- This will teach C++'s switch statement minus the feature of doing cases on classes.
- It will also introduce basic
enum
and how they work with switch statements. - I will show you how to add a
//falthrough
to document explicitly that you want to fall through a case, which helps catch missingbreak
. - Also talk about how it's not like if-statements which can do a lot of comparisons, but switch really only does integers. (Even classes get converted to an integer apparently).
View Source file ex13.cpp Only
#include <iostream>
#include <fmt/core.h>
using namespace std;
using namespace fmt;
enum color { RED, GREEN, BLUE};
int main() {
int which_door = 4;
switch(which_door) {
case 1:
println("DOOR #1");
break;
case 2:
println("DOOR #2");
// fallthrough
case 3:
println("DOOR #3");
break;
case 4:
println("DOOR #4");
break;
default:
println("BAD DOOR YOU DIED!");
}
color what_color = RED;
switch(what_color) {
case RED:
println("COLOR IS RED");
break;
case BLUE:
println("COLOR IS BLUE");
break;
case GREEN:
println("COLOR IS GREEN");
break;
default:
// how can you hit this?
println("BAD COLOR");
}
return 0;
}
Register for Learn C++ the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.