129k views
3 votes
What is wrong with the following switch statement, assuming temp is an int variable?

switch (temp) {
case temp < 0 : cout << "Temp is negative.\\";
break;
case temp == 0: cout << "Temp is zero.\\";
break;
case temp > 0 : cout << "Temp is positive.\\";
break;
}

User Ryotsu
by
7.5k points

1 Answer

2 votes

Final answer:

The switch statement in the question is not syntactically correct and should be modified to use constant values in the cases.

Step-by-step explanation:

The issue with the switch statement in the question is that it is not syntactically correct. The cases in a switch statement should contain constant values, not boolean expressions or comparisons. In this case, the cases should be modified to have constant values, such as:

switch (temp) { case -1: cout << "Temp is negative." << endl;break; case 0: cout << "Temp is zero." << endl;break; case 1: cout << "Temp is positive." << endl;break; }

Now the switch statement will compare the value of 'temp' with the constant values -1, 0, and 1, and execute the corresponding case.

User Blessy
by
8.0k points