Navigation



5.3 — Switch statements

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

enum Colors
{
    COLOR_BLACK,
    COLOR_WHITE,
    COLOR_RED,
    COLOR_GREEN,
    COLOR_BLUE,
};

void PrintColor(Colors eColor)
{
    using namespace std;
    if (eColor == COLOR_BLACK)
        cout << "Black";
    else if (eColor == COLOR_WHITE)
        cout << "White";
    else if (eColor == COLOR_RED)
        cout << "Red";
    else if (eColor == COLOR_GREEN)
        cout << "Green";
    else if (eColor == COLOR_BLUE)
        cout << "Blue";
    else
        cout << "Unknown";
}

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:

void PrintColor(Colors eColor)
{
    using namespace std;
    switch (eColor)
    {
        case COLOR_BLACK:
            cout << "Black";
            break;
        case COLOR_WHITE:
            cout << "White";
            break;
        case COLOR_RED:
            cout << "Red";
            break;
        case COLOR_GREEN:
            cout << "Green";
            break;
        case COLOR_BLUE:
            cout << "Blue";
            break;
        default:
            cout << "Unknown";
            break;
    }
}

The overall idea behind switch statements is simple: the switch expression is evalutated 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 code under the default label is executed (if it exists).

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

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, 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.

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 integral variable (such as nX, when nX 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. Typically, we end each case with a break statement, which tells the compiler that we are done with the case.

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

switch (nX)
{
    case 4:
    case 4:  // illegal -- already used value 4!
    case COLOR_BLUE: // illegal, COLOR_BLUE evaluates to 4!
};

It is possible to have multiple case labels refer to the same statements. The following function uses multiple cases to test if the cChar parameter is an ASCII number.

bool IsNumber(char cChar)
{
    switch (cChar)
    {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            return true;
        default:
            return false;
    }
}

If any of the case labels match, the next statement is executed. In this case, that is the statement return true;, which returns the value true to the caller.

The second kind of label is the default label, 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. It is also typically declared as the last label in the switch block, though this is not strictly necessary.

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 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 conditions are met, cases will overflow into other cases! Consider the following program:

switch (2)
{
   case 1: // Does not match -- skipped
       cout << 1 << endl;
   case 2: // Match!  Execution begins at the next statement
       cout << 2 << endl; // Execution begins here
   case 3:
       cout << 3 << endl; // This is also executed
   case 4:
       cout << 4 << endl; // This is also executed
   default:
       cout << 5 << endl; // This is also executed
}

This program prints the result:

2
3
4
5

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.

In order to prevent fall-through, we have to use a break, a return, or a goto statement at the end of our case statements. A return statement terminates the current function immediately, and a value is possibly returned to the caller. This makes a lot of sense in short functions with a single purpose, such as the IsNumber() function example above.

However, it is often the case that we want to terminate the case statements without also terminating the entire function. To do this, we use a break statement. 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), and execution continues with the statement after the end of the switch block.

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

switch (2)
{
   case 1: // Does not match -- skipped
       cout << 1 << endl;
       break;
   case 2: // Match!  Execution begins at the next statement
       cout << 2 << endl; // Execution begins here
       break; // Break terminates the switch statement
   case 3:
       cout << 3 << endl;
       break;
   case 4:
       cout << 4 << endl;
       break;
   default:
       cout << 5 << endl;
       break;
}
// Execution resumes here

Warning: Forgetting the break statements in a switch block is one of the most common C++ mistakes made!

Quiz

1) Write a function called Calculate() that takes two integers and a char representing one of the following mathematical operations: +, -, /, or *. 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 “Error” and the program should exit (use the exit() function).

Quiz answers

1) Show Solution

5.4 — Goto statements
Index
5.2 — If statements

63 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
    {
        COLOR_BLACK;
        COLOR_WHITE;
        COLOR_RED;
        COLOR_GREEN;
        COLOR_BLUE;
    };
    
    void PrintColor(Colors eColor)
    {
        using namespace std;
        switch (eColor)
        {
            case COLOR_BLACK:
                cout < < "Black";
                break;
            case COLOR_WHITE:
                cout << "White";
                break;
            case COLOR_RED:
                cout << "Red";
                break;
            case COLOR_GREEN:
                cout << "Green";
                break;
            case COLOR_BLUE:
                cout << "Blue";
                break;
            default:
                cout << "Unknown";
                break;
        }
    }
    
    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:

      int main()
      {
          Colors ePenColor = COLOR_BLACK;
          Colors eEraseColor = COLOR_WHITE;
      
          cout < < "I am drawing in: ";
          PrintColor(ePenColor);
          cout << endl;
          cout << "I am erasing in: ";
          PrintColor(eEraseColor);
          cout << endl;
      
          return 0;
      }
      

      This produces the result:

      I am drawing in: Black
      I am erasing in: White
      

      Not the most useful example, perhaps.

      Here's another example:

      int main()
      {
          while (1)
          {
              cout < < "Enter a character (ctrl-c to quit): ";
              char chChar;
              cin >> chChar;
              cout < < chChar << " is a ";
              if (IsNumber(chChar))
                  cout << "number" << endl;
              else
                  cout << "letter" << endl;
          };
          return 0;
      }
      

      Sample output:

      Enter a character (ctrl-c to quit): w
      w is a letter
      Enter a character (ctrl-c to quit): 3
      3 is a number
      Enter a character (ctrl-c to quit): 8
      8 is a number
      Enter a character (ctrl-c to quit): q
      q is a letter
      Enter a character (ctrl-c to quit):
      
  • 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.

  • Tom

    Alex -

    There is a logical error in the quiz question and answer: If we pass e.g. 1,2,- or 1,-1,* to the function Calculate, it will return a -1, which is our error code, when in fact an error has not occured since -1 is the correct result (2 – 1 = -1, 1 * -1 = -1). Wouldn’t it be much better to return the string value “ERROR” instead?
    i.e.:

    default:
              return "ERROR";
    
    • You are correct that this function contains a logic error in this regard. I’ll change the question and answer to avoid this issue.

      Returning an error string won’t work because the function is set up to return an integer. Incidentally, the function will also crash if the user tries to do a divide operation and the second parameter (the denominator) is 0.

  • 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:

    ...
    case '/':
        if (nY == 0) {
            cout < < "ERROR.  Division by zero.";
            exit(2);
        }
        return (static_cast<double>(nX)) / nY;
    ...

    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.

  • [...] 2007 Prev/Next Posts « 5.1 — Control flow introduction | Home | 5.3 — Switch statements » Thursday, June 21st, 2007 at 10:01 [...]

  • Ronnie

    How come you did not use break statements in your solution ?

    • I didn’t use break statements because I used return statements instead. I wanted to return a different value to the caller for each case. Keep in mind that return statements cause the function to immediately return to the caller, thus the switch statement will stop executing at that point. Break is used to keep cases from overflowing into each other — but this also happens with a return, since the entire function stops executing. Thus, there’s no need to use a break statement in the cases where you are using a return.

  • William

    Wait, for the quiz answer, shouldn’t there be a ‘using namespace std;’ at the beginning of the function?

  • 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
    {
    private:
    char mUpKey;

    public:
    Car(char upKey):mUpKey(upKey){};
    bool getKeyPress( const char c)
    {
    const int up = static_cast(mUpKey);
    switch(c)
    {
    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:

      const int up = 5;
      switch (x)
      {
      case up: return 7;
      }
      

      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.

  • juvil

    example switch statement that converts number to char

  • [...] 2007 Prev/Next Posts « 5.3 — Switch statements | Home | 5.5 — While statements » Thursday, June 21st, 2007 at 6:55 [...]

  • Alfreda

    I tried writing a full application for the quiz question:

    I tried writing a full application for the quiz question:

    #include

    using namespace std;

    int nFirst = 0;
    int nSecond = 0;
    char chOperator = 0;
    int nAnswer = 0;

    int Calculate(int nFirst, int nSecond, char chOperator, int nAnswer);

    int main()
    {

    Calculate(nFirst, nSecond, chOperator, nAnswer);

    cout << “You entered ” << nFirst << ” , ” << nSecond << ” and ” << chOperator << endl;
    cout << nFirst << chOperator << nSecond << ” = ” << nAnswer << endl;

    return 0;
    }
    int Calculate(int nFirst, int nSecond, char chOperator, int nAnswer)
    {
    cout << “Please enter a number “<> nFirst;
    cout << “Please enter another number ” <> nSecond;
    cout << “Please anter an operation you would like to perform on these two numbers. Please use one of the following: + – * /” <> chOperator;
    switch (chOperator)
    {
    case ‘+’:
    nAnswer = nFirst + nSecond;
    break;
    case ‘-’:
    nAnswer = nFirst – nSecond;
    break;
    case ‘*’:
    nAnswer = nFirst * nSecond;
    break;
    case ‘/’:
    nAnswer = nFirst / nSecond;
    break;
    default:
    cout<<”Error! Please try again!” << endl;
    Calculate(nFirst, nSecond, chOperator, nAnswer);
    break;
    }
    }

    ( for some reason iostream wouldn’t appear in the box, but it’s there in the actual code )

    It print’s out “You entered 0,0 and 0″
    “0 0 = 0″

    and then it ends…

    Any idea what’s going wrong? :S

    PS. the

     tags don't seem to be working :S I managed to get it but then some of my code was missing...
    • Andrian

      I don’t understand what you want to know because ofcourse it prints out 0,0 and 0 because multiplying, adding or dividing….nothing changes 0(0 – 0 = 0 & 0 + 0 = 0).

      And also you’re not returning anything from your ‘int calculate’ function so it shouldn’t even compile.

  • Alfreda

    Every time I post my code bits of it are missing :S

  • chaos

    I learned plt scheme a few years ago, and in that language if statements are formed by a string of if’s followed by an else. I noticed that in c++, it seems to work in a similar way:

    int someFn(int x)
    {
         if (x == 0)
             return 0;
         if (x == 1 )
             return 1;
         else
             return -1;
    }
    

    When I compile a function containing a string of if’s similar to the example above, it works exactly the way I would expect. However, in your code, it seems that you would write the same function like this:

    int someFn(int x)
    {
         if (x == 0)
             return 0;
         else if (x == 1 )
             return 1;
         else
             return -1;
    }
    

    Is there any difference between this way of writing if statements and the way to which I am accustomed in c++?

  • Dheeraj Marwaha

    I am confussed with the following code. it is working fine. Can you explain the internal behavior of this code.. .How is works?
    void duff(register char *to, register char *from, register int count)
    {
    register int n=(count+7)/8;
    switch(count%8)
    {
    case 0:
    do{
    *to++ = *from++;
    case 7:
    *to++ = *from++;
    case 6:
    *to++ = *from++;
    case 5:
    *to++ = *from++;
    case 4:
    *to++ = *from++;
    case 3:
    *to++ = *from++;
    case 2:
    *to++ = *from++;
    case 1:
    *to++ = *from++;
    }while( –n >0);
    }
    }

  • Anthony
    #include "stdafx.h"
    #include <iostream>
    
    enum MathTypes
    {
    	Add,
    	add,
    	Subtract,
    	subtract,
    	Multiply,
    	multiply,
    	Divide,
    	divide
    };
    
    int Calculate(int x, int y,char MathType)
    {
    	using namespace std;
    	switch(MathType)
    	{
    	case Add:
    		cout << "Your answer is: " << x + y << endl;
    		break;
    	case Subtract:
    		cout << "Your answer is: " << x - y << endl;
    		break;
    	case Multiply:
    		cout << "Your answer is: " << x * y << endl;
    		break;
    	case Divide:
    		cout << "Your answer is: " << x / y << endl;
    		break;
    	default:
    		cout << "That is not a correct response, please choose Add, Subtract, Multiply, or Divide." << endl;
    		break;
    	}
    
    	return 0;
    }
    
    int main()
    {
    	using namespace std;
    
    	cout << "Type an integer" << endl;
    	int x;
    	cin >> x;
    	cout << "Type another integer" << endl;
    	int y;
    	cin >> y;
    	cout << "What would you like to do? Add, Subtract, Multiply, or Divide?" << endl;
    	char mathType;
    	cin >> mathType;
    	cout << "Your answer is:";
    	Calculate(x,y,mathType);
    
    	return 0;
    }
    

    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

    #include "stdafx.h"
    #include <iostream>
    
    enum MathTypes
    {
    	Add,
    	Subtract,
    	Multiply,
    	Divide,
    };
    
    int Calculate(int x, int y,MathTypes MathType)
    {
    	using namespace std;
    	switch(MathType)
    	{
    	case Add:
    		cout << "Your answer is: " << x + y << endl;
    		break;
    	case Subtract:
    		cout << "Your answer is: " << x - y << endl;
    		break;
    	case Multiply:
    		cout << "Your answer is: " << x * y << endl;
    		break;
    	case Divide:
    		cout << "Your answer is: " << x / y << endl;
    		break;
    	default:
    		cout << "That is not a correct response, please choose Add, Subtract, Multiply, or Divide." << endl;
    		break;
    	}
    
    	return 0;
    }
    
    int main()
    {
    	using namespace std;
    
    	cout << "Type an integer" << endl;
    	int x;
    	cin >> x;
    	cout << "Type another integer" << endl;
    	int y;
    	cin >> y;
    	cout << "What would you like to do:" << endl;
    	cout << "1)Add" << endl;
    	cout << "2) Subtract" << endl;
    	cout<< "3) Multiply" << endl;
    	cout << "4) Divide" << endl;
    	int operand;
    	cin >> operand;
    	MathTypes mathtype;
    	switch(operand)
    	{
    	case 1:
    		mathtype = Add;
    		break;
    	case 2:
    		mathtype = Subtract;
    		break;
    	case 3:
    		mathtype = Multiply;
    		break;
    	case 4:
    		mathtype = Divide;
    		break;
    	default:
    		cout << "That is not a correct selection" << endl;
    		break;
    	}
    	cout << "Your answer is: ";
    	Calculate(x,y,mathtype);
    
    	return 0;
    }
    
  • Denis

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

    
    default:
       cout << 5 << endl;
       break;
    

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

  • Will

    Hi, Alex.

    In the first quiz assignment it was not obvious to me that the exit() system call was part of the . Perhaps you should write a observation in the quiz explaining must be included in order to use exit().

  • enum colors
    {
    color_blue
    color_yellow
    color_red
    color_white
    }

    void print color (colors ecolor)

    {
    using namespace std.
    if(e_color == blue)
    cout << "blue" <<

    elseif (e_color == "yellow")
    cout << "yellow" <<

    elseif (e_color == "red)
    cout << "RED" <<

    }

    void print color
    {
    using namespace std.
    switch e_color

    {
    case color_black:
    cout <<"black"<<;

    case color_white:
    cout <<"white"<<

    case color_red:
    cout <<"red" <<;

    }
    }

  • zyrha jane geraldino

    hi can i get an installer for free about this program?

  • hadleedog

    Hi Alex,

    Great tutorial, is there any possibility of a pdf file in the future?

  • Compiler

    Hi Alex, Thanks alot for the very nice page you made and its really helpfull for dummies like me:-)

    Now I got a problem. Answering to this quize, before looking at your suggestion for solution I write the following program and compile it without any problem, but it doesnt seem that the calculate() is called from main().

    does it have to do with the way I call Calculate()?
    Thankful for a replay.

    #include “stdafx.h”
    #include

    void Calculate(int x, int y, char oPerand)
    {
    using namespace std;
    cout<>x;
    cout<>y;
    cout<>oPerand;
    switch (oPerand)
    {
    case ‘+’:
    cout<<"the result is: "<<x + y<<endl;
    case '*':
    cout<<"the result is: "<<x * y<<endl;
    case '/':
    cout<<"the result is: "<<x / y<<endl;
    case '-':
    cout<<"the result is: "<<x – y<<endl;
    default :
    cout<<"try again "<<endl;
    exit(1);

    }
    }

    int main()
    {
    Calculate;
    return 0;
    }

  • Compiler

    I tried to call the function this way:
    int main()
    {
    Calculate(); //Didnt work, calculation doesnt take zero arguments
    Calculate(int x,int y, char Operand); //didnt work either
    return 0;
    }

  • 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.

  • buffpony

    this code gives me the error: “Calculate cannot take one argument. What should i do?
    #include
    using namespace std;
    int num1, num2;
    char opp;
    int Calculate(int num1,int num2, char opp)
    {
    switch(opp)
    {
    case ‘+’ || ‘plus’:
    return num1+num2;
    case ‘-’:
    return num1-num2;
    case ‘*’:
    return num1*num2;
    case ‘/’:
    cout << "The first number is didided by the second";
    return num1/num2;
    default:
    cout << "Error-program will exit";
    exit(1);
    }
    }
    int main()
    {
    cout <> num1;
    cin >> num2;
    cout << "Please Enter an opperation symbol: " <> opp;
    Calculate(opp);
    }

    • buffpony

      Actually forget that…. i fixed it. it was stupid. now i get the error when the program runs. it lets me enter numbers and operations, but crashed when performing them.

  • Groovychicken
    #include "stdafx.h"
    #include
    #include 
    
    void CalculateEquation(int nX, char chX, int nY)
    {
    	using namespace std;
    
    	switch(chX)
    	{
    		case('+'):
    			cout << "The result of: " << nX << " " << chX << " " << nY << " is " << nX + nY << endl;
    			break;
    		case('-'):
    			cout << "The result of: " << nX << " " << chX << " " << nY << " is " << nX - nY << endl;
    			break;
    		case('*'):
    			cout << "The result of: " << nX << " " << chX << " " << nY << " is " << nX * nY << endl;
    			break;
    		case('/'):
    			cout << "The result of: " << nX << " " << chX << " " << nY << " is " << nX / nY << endl;
    			break;
    		default:
    			cout << "ERROR!" << endl;
    			exit(0);
    	}
    }
    
    int main()
    {
    	using namespace std;
    
    	cout <> nX;
    	cout << "You have entered: " << nX << " as your first integer. " << endl;
    
    	cout <> chX;
    	cout << "You have entered: " << chX << " as your mathematical operator. " << endl;
    
    	cout <> nY;
    	cout << "You have entered: " << nY << " as your second integer. " << endl;
    
    	CalculateEquation(nX,chX,nY);
    
    	return 0;
    }
    
    
    		
  • SelfExplanatory

    In your solution for the quiz, wouldn’t (case ‘/’: return nX / nY) use integer division and return an incorrect value?

  • C++_4_fun

    Hi,
    I tried to write a program using the function in the quiz to do basic calculation with no success. I’m not sure what I’m doing wrong but when I try to print the value returned to Calculate(x, y, chOperator) by the arguments in the switch I get gibberish. The code is below. Any advice is appreciated.

    #include "stdafx.h"
    #include
    using namespace std;
    
    int Calculate(int x, int y, char chOperator)
    {
    	switch (chOperator)
    	{
    	case '+':
    			return x + y;
    			break;
    	case '-':
    			return x - y;
    			break;
    		case '*':
    			return x * y;
    			break;
    		case '/':
    			return x/y;
    			break;
    	}
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	using namespace std;
    	cout <> x;
    	cout << endl <> y;
    	cout << endl <> chOperator;
    	Calculate(x, y, chOperator);
    	cout << "The answer is: " << endl << Calculate(x, y, chOperator);
    
    	return 0;
    }
    
    
    		
    • C++_4_fun

      ?? Somo of my code was missing…
      The main section should have read

      int _tmain(int argc, _TCHAR* argv[])
      {
      	using namespace std;
      	cout <> x;
      	cout << endl <> y;
      	cout << endl <> chOperator;
      	Calculate(x, y, chOperator);
      	cout << "The answer is: " << endl << Calculate(x, y, chOperator);
      
      	return 0;
      }
      
      
      		
  • C++_4_fun

    Sorry, I’m not sure why some of the code is still missing. Any suggestions?

  • future_grim

    I’m having trouble trying to run my code, can someone tell me why its not working?

    #include “stdafx.h”
    #include
    #include

    using namespace std;

    int Input()
    {
    cout << "Input first number" <> nX;
    cout << "Input second number" <> nY;
    cout << "Input operation" <> chOperator;
    Calculate();
    }

    int Calculate(int nX, int nY, char chOperator)
    {
    switch (chOperator)
    {
    case ‘+’:
    return nX + nY;
    case ‘-’:
    return nX – nY;
    case ‘*’:
    return nX * nY;
    case ‘/’:
    return nX / nY;
    default:
    cout << "Error" << endl;
    exit(0);
    }
    }

    int main ()
    {
    Input();
    Calculate();
    }

  • Mythio

    Most obvious reason for not working would be that your not passing parameters to the calculate(); operation in the Input function.

    Other stuff to look at for:

    1. Input doesn’t return anything, i.e. it is not a function so use void Input();
    2. The call to calculate in main is not necessary (and missing parameters and wont work)
    3. The calculate function is called inside the input statement, however you need to use forward declaration of calculate() to make this work OR put calculate() before input().

    Hope it helps, Mythio

  • 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.

  • activatedgeek

    #include
    #include

    using namespace std;

    float input1()
    {
    cout<> x;
    return x;
    }

    float input2()
    {
    cout<> x;
    return x;
    }

    char cOperator()
    {
    cout<> Op;
    return Op;
    }

    float Result(float x, float y, char cOperator)
    {
    switch (cOperator)
    {
    case ‘+’ :
    return x+y;
    cout<< "\nThe sum of " << x << " and " << y << " is: " << x+y << endl;
    break; //reference 1

    case ‘-’ :
    return x-y;
    cout<< "\nThe subtraction of " << x <<" and " << y << " gives: " << x-y << endl;
    break;

    case '*':
    return x*y;
    cout<< "\nThe product of " << x << " and " << y << " is: " << x*y << endl;
    break;

    case '/':
    return x/y;
    cout<< "\nThe division of " << x << " and " << y << " gives: " << x/y << endl;
    break;

    default:
    cout<< "Error!" <<endl;
    exit(1);
    }

    }

    int main()
    {
    float number1 = input1();

    float number2 = input2();

    char Op = cOperator();

    Result(number1, number2, Op);

    cout<< Result(number1, number2, Op) << endl; // reference 2

    return 0;

    }

    The above program compiles, but i wanted the “cout” (reference 1 ==> look in the code) I defined under the cases in switch operator to be printed on the screen. Please anyone help, how do i do that?
    All I see is just the result printed as I defined in the main function (reference 2 ==> check the comments in above code)

  • Shailesh Joshi

    as i compiled answer of question no.1 in the quiz in code::blocks, it gives an like “exit were not declared in this scope. how to fix it? or i did something wrong??

  • DrSuse

    Important!!
    Using the Gnu C++ compiler on Linux (can’t speak for other platforms), you must include a library in order for “exit(1)” to compile:

    #include cstdlib (enclose “cstdlib” in the appropriate brackets)

    Failure to do so will result in compiler errors:

    error: ‘exit’ was not defined in this scope.

    Using stdlib.h (not stdlib) was also effective.

  • DrSuse

    Completed (working) code:

    #include <iostream>
    #include <cstdlib>
    double Calculate(char chOp, double dX, double dY)
    {
            using namespace std;
            switch (chOp)
            {
                case '+':
                    return dX + dY;
                case '-':
                    return dX - dY;
                case '*':
                    return dX * dY;
                case '/':
                    return dX / dY;
                default:
                    cout << "Error" << endl;
                    exit(1);
            }
    }
    
    int main()
    {
        using namespace std;
    
        cout << "1st number: ";
        double dX;
        cin >> dX;
        cout << "Enter "+","-","*", or "/" ";
        char chOp;
        cin >> chOp;
        cout << "2nd number: ";
        double dY;
        cin >> dY;
        cout << "The answer is: " << Calculate(chOp, dX, dY) << endl;
        return 0;
    }
  • Tinkerplus92

    int Calculate (int x, char a, int y){
    switch (a){
    case ‘+’:
    cout << x + y << endl;
    break;
    case '-':
    cout << x – y << endl;
    break;
    case '/':
    {
    if (x == 0 || y == 0)
    cout << "Cannot divide by zero." << endl;
    else
    cout << x / y << endl;
    }
    break;
    case '*':
    cout << x * y << endl;
    break;
    default:
    cout << "Did not enter valid operation." << endl;
    break;
    return 0;
    }
    }

  • sush tiwari

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

    which one is faster switch or if else? why?

  • Blackout
    <p>"What"</p>

    if you are wondering what I am doing, I am just testing something.

  • Blackout

    Never mind, it didn’t work.

  • Acedia

    #include “stdafx.h”
    #include

    using namespace std;

    int getInt() // Gets an Integer and Returns it
    {
    cout <> nInt;
    return nInt;
    }

    char getChar() //gets an Char and returns it
    {
    cout <> cTransOp;
    return cTransOp;
    }

    double Calculate(int nX, int nY, char cOp)
    {
    switch (cOp)
    {
    case ‘+’: return nX+nY;
    break;
    case ‘-’: return nX-nY;
    break;
    case ‘*’: return nX*nY;
    break;
    case ‘/’: return nX/nY;
    break;
    default: cout << "Error" << endl;
    exit(-1);
    }
    }

    int main()
    {
    int nX = getInt();
    char cTransOp = getChar();
    int nY = getInt();
    double dResult = Calculate(nX, nY, cTransOp);
    cout << dResult;
    return 0;
    }

    Enter a number: 4
    Enter an Operator: -
    Enter a number: Error

    Exit with Code -1 (0xffffffff)

  • Speeds03

    Why in the world won’t my code work!!!


    #include “stdafx.h”
    #include

    //This does not work!
    using namespace std;

    int Calculate(int nX, char chOperator, int nY)
    {
    switch (chOperator)
    {
    case ‘+’:
    return nX + nY;
    case ‘-’:
    return nX – nY;
    case ‘*’:
    return nX * nY;
    case ‘/’:
    return nX / nY;
    default:
    cout << "Error" << endl;
    exit(1);
    }
    }

    int main()
    {
    cout <> nX;

    cout <> chOperator;

    cout <> nY;

    cout << "Your answer is: ";

    Calculate(nX, chOperator, nY);

    return 0;
    }
    "

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

  • asoud

    how can i Write a C++ program to display cities of Saudi Arabia using switch case
    1)Riyadh
    2)Jeddah
    3)Dammam
    4)Makkah
    5)Madinah
    6)Abha

  • Hookah12

    Hello all. I was curious as to why I can’t seem to get negative values to be calculated with the function. For example, if I put in 5 for my first number, a (-) sign, and any number >5, (i.e. anything I expect to return a negative value) for the second, the program ends with exit code 253 but does not give a value (I also have the same issue with multiplication and division but feel subtraction is the simpler case). I tried explicitly initializing the integers as signed, but still can’t produce a negative number. Maybe I need to do something on the return line to specify a signed return value ? Any help would be appreciated.

You must be logged in to post a comment.