5.3 — Switch statements

Although it is possible to chain many if-else statements together, this is difficult to read. Consider the following program:

Because doing if-else chains on a single variable testing for equality is so common, C++ provides an alternative conditional branching operator called a switch. Here is the same program as above in switch form:

The overall idea behind switch statements is simple: the switch expression is evaluated to produce a value, and each case label is tested against this value for equality. If a case label matches, the statements after the case label are executed. If no case label matches the switch expression, the statements after the default label are executed (if it exists).

Because of the way they are implemented, switch statements are typically more efficient than if-else chains.

Let’s examine each of these concepts in more detail.

Starting a switch

We start a switch statement by using the switch keyword, followed by the expression that we would like to evaluate. Typically this expression is just a single variable, but it can be something more complex like nX + 2 or nX - nY. The one restriction on this expression is that it must evaluate to an integral type (that is, char, short, int, long, long long, or enum). Floating point variables and other non-integral types may not be used here.

Following the switch expression, we declare a block. Inside the block, we use labels to define all of the values we want to test for equality. There are two kinds of labels.

Case labels

The first kind of label is the case label, which is declared using the case keyword, and followed by a constant expression. A constant expression is one that evaluates to a constant value -- in other words, either a literal (such as 5), an enum (such as COLOR_RED), or a constant variable (such as x, when x has been defined as a const int).

The constant expression following the case label is tested for equality against the expression following the switch keyword. If they match, the code under the case label is executed.

It is worth noting that all case label expressions must evaluate to a unique value. That is, you can not do this:

It is possible to have multiple case labels refer to the same statements. The following function uses multiple cases to test if the ‘c’ parameter is an ASCII digit.

In the case where c is an ASCII digit, the first statement after the matching case statement is executed, which is “return true”.

The default label

The second kind of label is the default label (often called the “default case”), which is declared using the default keyword. The code under this label gets executed if none of the cases match the switch expression. The default label is optional, and there can only be one default label per switch statement. It is also typically declared as the last label in the switch block, though this is not strictly necessary.

In the isDigit() example above, if c is not an ASCII digit, the default case executes and returns false.

Switch execution and fall-through

One of the trickiest things about case statements is the way in which execution proceeds when a case is matched. When a case is matched (or the default is executed), execution begins at the first statement following that label and continues until one of the following termination conditions is true:
1) The end of the switch block is reached
2) A return statement occurs
3) A goto statement occurs
4) A break statement occurs

Note that if none of these termination conditions are met, cases will overflow into subsequent cases! Consider the following snippet:

This snippet prints the result:


This is probably not what we wanted! When execution flows from one case into another case, this is called fall-through. Fall-through is almost never desired by the programmer, so in the rare case where it is, it is common practice to leave a comment stating that the fall-through is intentional.

Break statements

A break statement (declared using the break keyword) tells the compiler that we are done with this switch (or while, do while, or for loop). After a break statement is encountered, execution continues with the statement after the end of the switch block.

Let’s look at our last example with break statements properly inserted:

Now, when case 2 matches, the integer 2 will be output, and the break statement will cause the switch to terminate. The other cases are skipped.

Warning: Forgetting the break statement at the end of the case statements is one of the most common C++ mistakes made!

Multiple statements inside a switch block

One other bit of weirdness about switches is that you can have multiple statements underneath each case without defining a new block.

Variable declaration and initialization inside case statements

You can declare, but not initialize, variables inside the case statements:

Note that although variable y was defined in case 1, it was used in case 2 as well. All cases are considered part of the same scope, so a declaration in one case can be used in subsequent cases.

This may seem a bit counter-intuitive, so let’s examine why. When you define a local variable like “int y;”, the variable isn’t created at that point -- it’s actually created at the start of the block it’s declared in. However, it is not visible (in scope) until the point of declaration. The declaration statement doesn’t need to execute -- it just tells the compiler that the variable can be used past that point. So with that in mind, it’s a little less weird that a variable declared in one case statement can be used in another cases statement, even if the case statement that declares the variable is never executed.

However, initialization of variables directly underneath a case label is disallowed, and will cause a compile error. This is because initializing a variable does require execution, and the case statement containing the initialization may not be executed!

If a case needs to define and/or initialize a new variable, best practice is to do so inside a block underneath the case statement:

Rule: If defining variables used in a case statement, do so in a block inside the case (or before the switch if appropriate)


1) Write a function called calculate() that takes two integers and a char representing one of the following mathematical operations: +, -, *, /, or % (modulus). Use a switch statement to perform the appropriate mathematical operation on the integers, and return the result. If an invalid operator is passed into the function, the function should print an error. For the division operator, do an integer division.

2) Define an enum (or enum class, if using a C++11 capable compiler) named Animal that contains the following animals: pig, chicken, goat, cat, dog, ostrich. Write a function named getAnimalName() that takes an Animal parameter and uses a switch statement to return the name for that animal as a std::string. Write another function named printNumberOfLegs() that uses a switch statement to print the number of legs each animal walks on. Make sure both functions have a default case that prints an error message. Call printNumberOfLegs() from main() with a cat and a chicken. Your output should look like this:

A cat has 4 legs.
A chicken has 2 legs.

Quiz answers

1) Show Solution

2) Show Solution

5.4 -- Goto statements
5.2 -- If statements

136 comments to 5.3 — Switch statements

  • Allen01

    Alex, could you show one or two programs from the examples above worked fully? for example, could you show how the code below might evaluate in the main function. Thanks. Also, shouldn’t the symbolic constant enumerators in the “enum Colors” block end with a ‘,’ instead of a ‘;’?

    enum Colors
    void PrintColor(Colors eColor)
        using namespace std;
        switch (eColor)
            case COLOR_BLACK:
                cout < < "Black";
            case COLOR_WHITE:
                cout << "White";
            case COLOR_RED:
                cout << "Red";
            case COLOR_GREEN:
                cout << "Green";
            case COLOR_BLUE:
                cout << "Blue";
                cout << "Unknown";
    int Main()
    // Please show how the code in the above blocks might evaluate.
    • You’re right, the enums should be separated by commas, not semicolons. I fixed the example.

      Here’s a piece of sample code:

      This produces the result:

      Not the most useful example, perhaps.

      Here’s another example:

      Sample output:

  • Allen01

    Thanks for the examples. I have another question: What are the rules for adding a semi-colon to the end of a block? If I remove the semi-colon from the end of the enum Colors block, it will not compile.

    • As far as I can tell, all statements should be terminated by a semicolon, EXCEPT for compound statements (blocks).

      A declaration is considered a statement, and thus should be terminated by a semicolon. An enum is a declaration so it needs to be terminated with a semicolon. Same with a class declaration. The statements inside a switch are considered compound statements, so they do not need a terminating semicolon.

  • Jeff

    In a real-world application, where we are concerned with the possible perils of integer division, would it be better to have Calculate() return a double? And, if so, does the following work:

    Will the other cases (e.g., addition of two integers) automatically convert the integer sum to a double return value without the compiler complaining?

    • Whether it’s more appropriate to return an int or a double depends entirely on your needs. For some tasks, integer division might be exactly what you want. Others, maybe not. If your function is going to return a double, you might want to modify it to take double parameters as well so you can do floating point addition, subtraction, and multiplication.

      I believe your case would work as you intend. And yes, an integer return value will be implicitly converted to a double if the function has been declared to return a double.

  • siku

    My car class doesn’t compile. Compiler gives me error “C2051: case expression not constant”. Although I have defined a constant integral variable ( const int up = (int) mUpKey). I worked around this problem using if else statements but I am still interested to solve it by using switch statement. Can you explain why switch doesn’t work because I have a constant expression after case.

    Here is the example code:

    class Car
    char mUpKey;

    Car(char upKey):mUpKey(upKey){};
    bool getKeyPress( const char c)
    const int up = static_cast(mUpKey);
    case up:
    //move(0, 1);
    return true;

    return false;

    • Aah, you’ve run across a very interesting case here. Case statements have to be statements that are essentially compile-time constants. So something like this will work:

      This works because up is a constant at compile time.

      However, in your case, your value of up is dependent upon the value of mUpKey, which can vary depending on the instance of Car. So even though your value of up has been made const, it’s not a compile-time constant.

      • siku

        Thanks for your reply. In that case I would not change my code to use switch statement because it would not allow users to set one’s keys later.

  • Anthony

    This code does not give the expected results, any clue why? It compiles, it just doesn’t do what it should do.

    • Anthony

      I updated it with this code, but there has to be a better way, lol

    • Helvetica Standard

      6 years late so the guy I’m replying to is probably a veteran programmer now, but I modified his code a bit to make it work - both for my own pratice, and because I found the idea of letting the user enter "add" "Subtract" etc to select the operator in the program interesting.

  • Denis

    Is it necessary to use the break statement following the default code? For example -

    It seems rather redundant. Is there a practical purpose for doing so?

    • Alex

      It’s not redundant, it’s superfluous. 🙂

      The only reason that you’d need to include a break at the end of your default case is if the default case wasn’t the last case. In that case, anything that matched the default case would fall-through to the cases below.

  • Jesper

    Hi Alex

    I want to say that i love these tutorials you’ve made. I’ve been away from
    c++ for some years and I needed a brush-up and this is just perfect. Great job!!
    I have something to add to this section on the switch-case construct though.
    The real reason why there is two ways to achieve the same thing i.e. if-elseif-else and switch-case
    is because of execution-speed. if-elseif-else will always execute in linear time while switch-case
    is implemented using a jump-table meaning it will execute in constant time. Though the jump-table
    will only be used if the case-values are not spread out too far, because that would make the
    jump-table too big.
    So if it is possible you should always use switch-case and keep switch-values in the low range.

  • tadepalli.vinay

    Can someone tell me why switch-case-default statements cannot use floating point values. I mean, i want the reason behind it. As I understand, SWITCH statements can make your program faster compared to the IF-ELSE ladder since it generates a jump table in the compilation without need to wait during execution time. But can’t it be done with floating-point values as well?
    Good Reasoning is required.

  • DrSuse

    Completed (working) code:

  • sush tiwari

    I Love this tutorial!!!!!!!!!! Alex u did a great JOB!!!!!!!!!

    which one is faster switch or if else? why?

    • Alex

      Switch, because of the way it’s implemented internally.

      A switch uses a jump table to quickly determine which set of statements to execute, whereas an if-else chain has to do one comparison per if-else condition.

      However, the downside of switches is that they are somewhat limited in what they can do.

  • What is the differtence between using RETURN or BREAK in the Switch CASE instruction?

    • Alex

      return exits the entire function that the switch is inside of and returns a value to the caller.
      break exits only the switch, and code execution continues below the switch statement.

  • Andy

    I have used every single thing that I learned in previous lessons to complete the quiz.
    Heck, I even used a boolean to check whether the user had already filled in a first operand and it worked.
    Now this is what motivates me to keep learning this awesome language!

    What I didn’t understand is why this gave me an error:

    I had to do this instead:

    If anyone could give me some further explanation on this, that would be highly appreciated!
    Note: This was inside a switch statement under main().

    Thank you for the lessons!


    • Snowman

      Hi, if you still wish for someone to help out, please post the full code. I cannot help with the snippet your provided.


      Ok, maybe I can. Functions return a value, switch statements are just complex ifs and ifs do not return a value but rather preform commands. Therefore, the return is not correct because it is trying to send a value nowhere, but the second snippet of cout, break preforms the cout then exits the switch as intended.

      tl;dr: switch statements cannot return a value in main, only in a function with a return type.

    • Alex

      cout prints something to the screen. What would it mean to return this to another function?

  • Snowman

    So I decided to take it a step further. This program takes a calculation as one long string input, can have multiple operators but will not calculate using BODMAS but rather in order of appearance.

    Eg. user enters 4+7*2-1
    Answer is: 21 (4+7=11, 11*2=22, 22-1=21)

    Just made it as a challenge. Used a C++11 command called stof (string to float). Program ignores whitespace.

    • Snowman

      Correction above, line 33 should be:

      Won’t cause an error, but is wrong none the less

  • Aacon

  • Jatn

    I ran the following code for question in code blocks and compiler showed me lots of messages and 2 errors

    The errors were like this
    C:\Documents and Settings\ADMIN\Desktop\Family\C++ Files\problems\main.cpp|68|error: no match for ‘operator<<‘ in ‘std::operator<< <std::char_traits<char> >((* & std::operator<< <char, std::char_traits<char>, std::allocator<char> >((* & std::operator<< <std::char_traits<char> >((* & std::cout), ((const char*)"A "))), (*(const std::basic_string<char>*)(& getAnimalName(Animal)())))), ((const char*)" has ")) << printNumberOfLegs(Cat)’|

    and the other one is

    C:\Documents and Settings\ADMIN\Desktop\Family\C++ Files\problems\main.cpp|69|error: no match for ‘operator<<‘ in ‘std::operator<< <std::char_traits<char> >((* & std::operator<< <char, std::char_traits<char>, std::allocator<char> >((* & std::operator<< <std::char_traits<char> >((* & std::cout), ((const char*)"A "))), (*(const std::basic_string<char>*)(& getAnimalName(Animal)())))), ((const char*)" has ")) << printNumberOfLegs(Chicken)’|

    Can anybody help….

    • Alex

      printNumberOfLegs() returns void, but you’re trying to send that void result into cout. You’ll need to break line 68 and 69 up like this:

      Or change printNumberOfLegs() to return a value.

  • Todd


    "Write a function called Calculate()" (in your solution, you write a function called ‘calculate()’, which is correct with first letter lowercase)

    Quiz 1 solution typos:

    Above, "Calculate():" should be "calculate():"

    Your main() function doesn’t have a ‘return’ statement.

    Quiz 2 solution typos:

    Above, instead of " walks on ", your quiz question requires us to write " has "

    Above, you should say "printNumberofLegs()", not "getNumberOfLegs()".
    Also above, ‘animal’ (of data type "Animal") cannot be printed here using std::cout (compiler error occurs). Maybe use stat_cast<int>(animal)

  • C++ newbie

    Hey there,

    in my code I had something like this in main:

  • devkkp


    1>c:\users\ganeshji\documents\visual studio 2010\projects\switch statements\switch statements\switch statements.cpp(61): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include "StdAfx.h"’ to your source?

  • cpplx

    quiz1… works properly but prints extra nonsense data in the error case. i object 🙂

  • splotz

    How could we change Quiz 2 to where the user inputs the animal name ?

    • Alex

      Dealing with text is complicated.

      Probably the easiest way would be to add code to do the following:
      * #include <string>
      * Instantiate a variable of type std::string in main().
      * Use std::cin to read in a string from the user
      * Write a function that takes the string as a parameter and returns the appropriate matching enum
      * Ensure your function works with different capitalizations of the string.

  • Shivam Tripathi

    @ If a case needs to define a new variable, you can do so by putting it inside a block underneath the case:

    switch (1)
        case 1:
        { // note addition of block here
            int x = 4; // now legal
            std::cout << x;
            std::cout << "default case" << std::endl;

    Correct me if m wrong…but i think that the "break" should come outside of the block…

  • Shivam Tripathi

    got it…thnx once again Alex…:)

  • techsavvy....aye

    Will you give an example of operating this snippet,

    Thanks in advance.

    • Alex

      Sorry, I’m not clear on what you mean. Are you asking for this snippet to be put inside a program that you can run?

      If so, by this point you should be able to do that yourself. This snippet is self-contained, so you should be able to toss it into an empty main() function and run the resulting program.

  • I am not sure but I think the Heading "Default labels" should be "The default label" because each switch can  contain only one default label.

  • Ed

    So im going to do two things. The first is a question on your solution. In the SWITCH function in the getAnimalName(), you dont have any BREAKs. Why doesnt this cause fall-through?

    the second is, I got my code to work (taking me a while to think things through logically), mine is mostly the same, however I do the following:

    My printNumberofLegs() is also a std::string instead of a void. So my questions is, would this be considered a sloppy way of doing it, and would instead of defining pig and chicken, should I just have used Animal::pig and Animal::chicken in the std::cout areas?


    PS: I saw that you just had your ANIMAL_PIG and such and it took me forever to realize you were using a ENUM not ENUM CLASS and thats why yours looked different.

  • Mr D

    Hi Alex,

    Could you explain why, in the snippet below, we get a print out of:
    2, 3, 4, 5 ?

    After matching case 2, why does it go on to match cases 3, 4 and 5, when in fact they don’t match?!

    • Alex

      That’s just the way they were designed. Switches start execution at the first matching case, and then keep executing until a break, return, goto, exit statement, or end of the switch is reached.

      You can see where this is useful in the isDigit() example above. More often than not, it’s a pain.

      If I were designing a switch statement for C++, I would have designed it the other way around: cases would implicitly break at the next case statement unless an explicit “fall-through” keyword was provided. But nobody asked me. 😛

  • Mr D

    Ah, ok, so after case 2 is matched, the compiler doesn’t look for (or care about) any more  "case" statements and just sees the

    parts and executes that?

  • Aryan

    Hey Alex!
    In the first solution you put return 0 inside the switch block rather than outside it. Does it make a difference. Because I think in your example the calculate() function does not return a value.

    • Alex

      In this case, it doesn’t make a difference. Since there’s a default case, we’re guaranteed that _some_ case will execute. And since all cases have a return statement, we’re guaranteed to hit a return statement before the switch executes.

      You could put a return statement after the switch just for safety, but for now it would never get executed.

  • I took your example program and ran it on Visual Studio 2013:

    #include "stdafx.h"
    #include <iostream>

    bool isDigit(char c)
        switch (c)
        case ‘0’: // if c is 0
        case ‘1’: // or if c is 1
        case ‘2’: // or if c is 2
        case ‘3’: // or if c is 3
        case ‘4’: // or if c is 4
        case ‘5’: // or if c is 5
        case ‘6’: // or if c is 6
        case ‘7’: // or if c is 7
        case ‘8’: // or if c is 8
        case ‘9’: // or if c is 9
            return true; // then return true
            return false;

    I get the following error with this program and your other switch examples:

    error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

    Is there a setting I need to change or do I need to include another library to resolve this problem?

  • Rob G.

    Hi Alex, exercise well done.

    I took the opportunity to static_cast the char and used switch statements with each ascii value. What a hoot.
    Overall, I am jealous I think your example is more elegant and simple. Is a prime opportunity to use static cast. Also, struct may be more efficient.

  • Jim

    I’m still having problems understanding your different uses of the word color.  In the first code above you have a function printColor it has (Colors color) after it as the argument.

    Can you please tell me if I have this right? There is one argument. Colors is the (Enum)type here and color is the variable used in the function printColor. Since there is never an assignment made to color (only comparisons) with the if/else statements below it the function just prints out: "unknown" (No Quotes).

    Now in the second code you have:
    switch (color) and none of the case statements are ever true so the default unknown is again printed out. Is this also right?  Thanks

    • Alex

      > There is one argument. Colors is the (Enum)type here and color is the variable used in the function printColor.


      > Since there is never an assignment made to color (only comparisons) with the if/else statements below it the function just prints out: “unknown” (No Quotes).

      False. Because this is a function parameter, the value of this variable will be set by the caller.

      For example, the caller may do something like this:

      When printColor is called, the color variable (of type Color) will be initialized with the enum value COLOR_BLACK.

      This isn’t any different to how function parameters work with fundamental data types, like integers or doubles.

  • Jazz

    Hi Alex,

    My question is about C++11 syntax usage in the second quiz. How can ‘Animal parameter’ gets into the function getAnimalName(???), in case if i’m using enum class, istead of plain enum? The same question related to switch(???) statement.

    • Alex

  • Hridayesh Sharma

    hey alex in this code i have declared a variable in one of the case statemnts and it is running fine.

    • Alex

      Yep, I made a mistake here. You are allowed to declare variables inside the cases and assign values to them, but not initialize them. I’ve updated the lesson to reflect this.

      • Hridayesh Sharma

        but Alex what is the use of restricting the initialization of a variable when  i can use the variable by first declaring it and then assiging a value to it. Or what specifically is the purpose of restrictiong the initialization of variables in switch case statements.
        Thanks btw for your quick response.

        • Alex

          It has to do with the way switch statements are implemented (they are essentially goto statement in disguise, and goto statements are not allowed to jump past initialized values in C++).

          In many cases you can simply declare and assign a value to the variable rather than provide an initializer, but there are other cases where this is not possible, such as const values or references, which require initialization.

          But really, it’s irrelevant, because declaring variables in a case outside of a block is something that should be avoided. Just put them in a block and be done with it.

  • Osman Zakir

    Why does Visual Studio keep putting a red line under operator<< after ‘"A "’ here?

    I know it means there’s an error, but I don’t get why it’s showing an error there.  Operator<< should be able to handle outputting strings.

    Edit: I overloaded operator<< to accept strings, but it ended up causing the program to crash when I run it. Please help.

  • Lokesh

    You do not need to use

    explicitly in the first example code inside printColor(), since you have used using directive

  • Lokesh

    In the solution to Quiz Q.1, you have used

    in the default case instead of a break. Since, this could be a valid answer, isn’t it error prone?
    Also, if I use break statement in the default case instead of a return statement, I get the following warning:
    In function ‘int calculate(int, int, char)’:
    test_45_switch_case.cpp:20:1: warning: control reaches end of non-void function [-Wreturn-type]
    Why is it so? Isn’t the control returning to the main() after the switch block is exited using break statement?

    • Alex

      > in the default case instead of a break. Since, this could be a valid answer, isn’t it error prone?

      Yes, absolutely. But we haven’t really talked about error handling yet, so I’m keeping things simple for now.

      > Isn’t the control returning to the main() after the switch block is exited using break statement?

      If you replace the returns with a break, the break exits the switch block (not the function), and then the function continues to run to the end. Once the function ends, control returns to main. So in that case you’ve reached the end of the function without providing a return statement, so what value would the function return in that case? I’m surprised it only gave you a warning and not an error.

  • saeid

    in quiz1 in your code :

    i think its better to use static_cast :

    what u think ?

  • Dyablo

    For some reason,

    gives me integer division, whereas,

    gives me floating point division. Can’t figure why that is

    • Alex

      The return type of the function is set to an int, so it’s implicitly converting the double result back to an integer before returning the value to the caller.

      • Shiva

        Alex, it seems like Mr. Dyablo copied your code, because the function you wrote too is set to return an int, not a double. (Todd-mode ON. B) )

        Variables declared inside a switch statement follow the normal scope and duration rules, don’t they? So a variable declared inside a case statement is destroyed at the end of the switch. Also it can be used inside other cases. Similarly, a variable declared inside a block within a case statement is destroyed at the end of the block, and is not accessible inside other case statements. Correct?

  • Nhav

    At quiz 2
    How should you even call the printNumberOfLegs() function to get the default case?

    Also if the default case would be picked wouldn’t you get the result : printNumberOfLegs(): Unhandled enumerator legs.  ?:))

    Cuz you put cout << "legs" after default case.

    • Alex

      As written, there’s no way to get the default case. The default case here is meant to ensure that if we ever add another enumerator and forget to update the function to account for the new enumerator, the output gives us some clue that we now have a case that isn’t handled properly. Yes, the output is funny in that case, but at least we _know_ it’s wrong, can look into it, and then fix the function.

  • Joshua Richards

    Very Small thing I noticed.

    In the very first example in this lesson you wrote an enum with a comma at the end of the last enumerator. I know this is not a big deal at all, and it would still compile, I just wanted to bear notice that I remembered that this is not proper conention when writing an enum. This is just proof of how great your tutorials are to remember such as minut detail thanks Alex!

  • Patrick

    I wrote much more code than Alex provided in his answer. Definitely an opportunity for me to write code more efficiently. This is why I like quizzes so much.

    I changed the return type value for a division to double as part of the first quiz answer. If first integer is smaller than the second integer then without type casting I get 0 returned because precision is dropped.



  • Edward Osei-Nyarko

    This code gives me errors when i compile;
    Error message:

    ||=== Build: Debug in Learncpp5.3 (compiler: GNU GCC Compiler) ===|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp||In function ‘double Calculate(char, double, double)’:|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|15|error: case label ”-” not within a switch statement|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|18|error: case label ”*” not within a switch statement|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|21|error: case label ”/” not within a switch statement|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|24|error: case label ”%” not within a switch statement|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|25|error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%’|
    C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|27|error: case label not within a switch statement|
    ||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 5 second(s)) ===|

  • Akhil

    Please help,i am unable to figure what’s wrong with this code

    • Alex

      consoleapplication1.cpp(90): error C4700: uninitialized local variable ‘cat’ used

      It looks like you’ve declared two animals (cat and chicken) but never initialized them. Should be:

  • J3ANP3T3R

    "All cases are considered part of the same scope, so a declaration in one case can be used in subsequent cases"

    sometimes i find that C++ does not make any sense. given that case will execute the next statement(s) if case evaluated to true until it encounters break, goto etc. that said "int y;" should not have executed and y should not have been declared.

    QUESTION : if the variable is declared inside a block will it still be visible in the rest of the cases ?

    • Nyap

      >QUESTION : if the variable is declared inside a block will it still be visible in the rest of the cases ?
      no unless you use keyword "static" - the variable will be destroyed at the end of the block

      >sometimes i find that C++ does not make any sense. given that case will execute the next statement(s) if case evaluated to true until it encounters break, goto etc. that said "int y;" should not have executed and y should not have been declared.
      I’m confused about that too :c

      • Nyap

        I’ve been chatting a bit on forums, and got this:

        So duration is what really matters. When the compiler compiles this:

        int y is created on line 2 and destroyed when the blocks ends. It can be used anywhere in that block. Execution path doesn’t matter

        • J3ANP3T3R

          oh i see… so it gathers all the variable declarations within the entire switch statement and sort of creates the variable at the start of the block ?

          • Nyap

            @J3ANP3T3R actually I made a mistake

            it can only be used anywhere under the declaration, however this is just a limitation set by the compiler. If it weren’t for scope, then you could just put it anywhere, and it would still compile and run perfectly. At least thats what I have gathered

            Forum post is here:

        • Alex


          Although in the above example, case 3 is not allowed, because initialization DOES require execution, and if case 3 never executes, what value would variable z have if the default path were selected? It would be undefined.

      • Alex

        Where a variable is visible (scope) and where it is created/destroyed (duration) are two different things. The static keyword affects duration, not scope. I made an update to this lesson to try to make how this works a little clearer. Have a re-read and let me know if you’re still confused.

    • Alex

      Yeah, switch statements are a bit weird. That’s why I try not to use them for anything other than trivial lookups (where the body for each case is simply a return statement).

      That said, when you define a variable like “int y;”, the variable isn’t created at that point -- it’s actually created at the start of the block it’s in. However, it is not visible (in scope) until the declaration. So with that in mind, it’s a little less weird that a variable defined in one switch case can still be used in later switch cases, even if the upper switch case doesn’t execute.

      As for the block question, anything declared inside a block is not visible to anything outside the block.

  • Nyap

    Whats a jump table

    • Nyap

      also, I don’t get how this works:
      [quote]Note that although variable y was defined in case 1, it was used in case 2 as well. All cases are considered part of the same scope, so a declaration in one case can be used in subsequent cases.[/quote]
      But doesn’t the declaration statement have to executed for the variable to be accessable?

      • Alex

        I just answered this in the above comment. Seems to be a popular question this week. 🙂 When you define a variable like “int y;”, the variable isn’t created at that point -- it’s actually created at the start of the block it’s in. However, it is not visible (in scope) until the declaration. So with that in mind, it’s a little less weird that a variable defined in one switch case can still be used in later switch cases, even if the upper switch case doesn’t execute.

        I’ll add a little more about this to the lesson itself.

    • Alex

      Abstractly, a jump table is a table (array) of instructions that “jump” the point of execution to a different place in the code (using some other value to select which branch to take).

      In C++, a switch statement acts as a form of jump table itself. Your switch provides the value to jump to, and the point of execution jumps directly to the case statement that matches. This is often more efficient than using a series of if/else statement.

      An array of function pointers also acts like a jump table.

  • subh

    I wanted to modify question-2 so that it will only print the animal entered by the user.  I tried to modify the main(), but I am not able to write proper switch() or if else statement. Can you help?

    int main()
    std::string x;
    cout<<"enter the name of an animal\n";
    cin>> x;
        if ( x == ‘cat’)
        else if (x == ‘chicken’)
        return 0;

    • Alex

      Your if statement is fine, but “cat” and “chicken” need to be in double quotes. Double quotes are for strings, single quotes for single chars.

  • Hello Alex am learning a lot with your site  but please could you show an example with the example you have illustrated in your tutorials. How do i start such an example from the the start then i continue from where you started in your example thats dealing with colors.

  • Hugh O'Brien

    For some reason this won’t compile. Its telling me there’s an unexpected end of file when searching for precompiled header?

    Love the tutorials by the way 🙂

    • Alex

      Compiles fine for me. Sounds like maybe your stdafx.h is corrupt somehow. Try recreating your project.

      • Hugh O'Brien

        Ya thanks, I figured it out. It was just that I was using an old file the I’d previously used and in microsoft visual there was a two tabs (one being source tab). When I recreated the code in a new file there was no source tab and it all worked fine. Unfortunately I don’t yet understand the UI of microsoft visual because I’m a newby. In time… Thanks for you reply 🙂

  • Omar Farrag

  • Kenneth

    Quiz 1 solution, compiles and seems to work just fine, except that the console prints "Invalid operator selected!" before "Results:".  Just curious why this happens.  Fantastic tutorial by the way!  Loving it!

    • Alex

      When I compiled this with Visual Studio 2015 and tried a couple of inputs (5 3 + and 5 3 -) it worked fine. I don’t see anything wrong (though the break statements in DoMath() are extraneous and can be removed).

      • Kenneth

        I should have clarified that better, I was referring to if I put in something other than one of the four basic operators
        (5 3 g for example).

        • Alex

          Function calls have higher precedence than operator<<, so DoMath() is evaluated before the other statements are printed. One way to fix this would be to have DoMath() return the result as a std::string instead of printing the value itself.

  • Matt

    I think I remember you teaching us that variables declared inside of if/else blocks are not visible outside of the block. Does the same thing go for variables declared within a switch?

    If not, then what about declaring a variable within a block, within a case statement…. will that variable be visible outside of that block and outside of the switch statement?

    • Alex

      Variable declared in a block are only visible in the block in which they are declared, or in any sub-blocks.

      So for variables declared in a switch block or case block, those will only be visible in those blocks.

  • Georges Theodosiou

    Mr Alex, good morning,

    Please let me report you my problem. I use compiler coliru ( and output is in quotes:

    main.cpp: In function ‘int main()’:

    main.cpp:30:28: error: ‘printColors’ was not declared in this scope



    With regards and friendship
    Georges Theodosiou
    The Straw Man

  • Georges Theodosiou

    Mr Alex, good afternoon (I live in France),

    Please accept my many thanks for fixing. Now it functions perfect.

    With regards and friendship
    Georges Theodosiou
    The Straw Man

  • M Hassan Tahir

    In the quiz exercise (2), i want to get the animal name input from the user but i cant find a way to do so.

    Error: no suitable conversion function from "std::string" to "Animal" exists.

    Need some help in this case plz. Thanks!

    • Alex

      Yes, the problem here is that x is a std::string, and you are passing x as an argument to function getAnimalName(), but getAnimalName() has a parameter of type Animal. The compiler doesn’t know how to convert a string to an animal.

      So you’ll need to do this conversion yourself. The easiest way to do this is to write a function to do the conversion:

      • sambhav beniwal

        how to take a input off data type ‘Animal’ directly ?

        here, since it is giving an there a possble way to take input of animal directly from user ?

        • Alex

          Read the user’s input as a std::string, then write a function to convert the std::string to an Animal.


      • sambhav beniwal

            using namespace std;
            enum Animal

            void getAnimalName(Animal animal)
                switch (animal)
                    case pig:
                    case chicken:
                    case goat:
                    case cat:
                    case dog:
                    case ostrich:
                    cout<<"invalid choice";
            int printNumberOfLegs(Animal animal)
                    case pig:
                    return 4;
                    case chicken:
                    return 2;
                    case goat:
                    return 4;
                    case cat:
                    return 4;
                    case dog:
                    return 4;
                    case ostrich:
                    return 2;
                    cout<<"\tinvalid choice\t";
                    return 0;
            int main()
                int x;

        here, cout<<"A\t"<<(getAnimalName(pig))<<"\thas\t"<<x<<"\tlegs.";
        why isn’t cout possible this way ??

        • Alex

          Your getAnimalName() returns a void, and you can’t send a void value to std::cout.

          If you make getAnimalName() return a std::string instead of void, then this should work.

  • J

    ? Im doing a java course which by the way is a breeze thanks to what I learned on here so Thanks for the awesome tut. My ? is in java switch statement conditional expression can also evaluate to a string is this not true in C++ also ?

    • Alex

      In C++, a switch must be an integer or enumeration type (or a class that is convertable to such). So basically, no, you can’t switch on a string in C++.

      • J

        Thanks for the reply maybe they will add that ability later it would be nice

        • Alex

          I think that’s unlikely to ever happen in C++ (it would be quite inefficient).

          For now, you can use a sequence of if/else statements. If you want something maybe more efficient, you can set up a std::map to map strings to enums, and then switch on the enums.

  • Avijit Pandey

    here is what i wrote

    Although i am using a C++11 capable compiler(GNU CC Compiler),but if i use enum class instead of enum, my compiler says that all the animals (PIG,CHICKEN,…) are not defined in this scope in getAnimalName() and printNumberOFLegs() functions.
    so why did you advice to use the enum class?
    or am i doing something wrong?

    • Alex

      You’re doing something wrong. 🙂

      If you use an enum class, then your enumerators need to be prefixed with the enumeration name. e.g. instead of CAT, you need to use Animals::CAT.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter