Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect Multiple Cases in Switch not generating compiler error [duplicate]

Tags:

c++

I know that this code does not work as "expected". Just looking quickly at this code, we think the return value should be 1, but in the execution it returns returns 3.

// incorrect
variable = 1;
switch (variable)
{
  case 1, 2:
    return 1;
  case 3, 4:
    return 2;
  default:
    return 3;
}

and there are some correct options to do this:

// correct 1
variable = 1;
switch (variable)
{
  case 1: case 2:
    return 1;
  case 3: case 4:
    return 2;
  default:
    return 3;
}

or

// correct 2
switch (variable)
{
  case 1:
  case 2:
    return 1;
  case 3:
  case 4:
    return 2;
  default:
    return 3;
}

This is partially answered in Multiple Cases in Switch:

I would like to know why the incorrect form does compile without error or even warnings (at least in the Borland C++ compiler).

What does the compiler understand in that code?

like image 342
Juliano Avatar asked Nov 13 '15 13:11

Juliano


2 Answers

Just looking quickly at this code, we think the return value should be 1,

I'd say that an experienced C++ developer would immediately notice that something is wrong and quickly conclude that some other programmer accidentally tried to use the comma operator: ,

but in the execution it returns returns 3.

No, the code must not compile, because the case expression is not constant

And as a matter of fact, it does not compile in any halfway modern compiler. For example, MSVC 2013 says:

stackoverflow.cpp(8) : error C2051: case expression not constant
stackoverflow.cpp(10) : error C2051: case expression not constant

An expression like 1, 2 is an application of the comma operator, and the comma operator implies that the expression is not a compile-time constant.

At least until C++11 came along and relaxed the rules to the effect that adding parentheses, i.e. case (1, 2):, would be allowed to compile. It just would not do what you seem to expect.

This is partially answered in Multiple Cases in Switch:

How so? That other question and the answers are almost exclusively about C#, not about C++.

I would like to know why the incorrect form does compile without error or event warnings (at least in the Borland C++ compiler).

Because the compiler is too old. Better get a new one.

like image 69
Christian Hackl Avatar answered Nov 15 '22 06:11

Christian Hackl


My guess is that in the first case the compiler evaluates the comma operators to result in the code being executed as follows:

switch(variable)
{
  case 2:
    return 1;
  case 4:
    return 2;
  default:
    return 3;
}

From above, it can be seen why the value 3 is returned for input 1. I suggest you read up about the comma operator. There are some excellent threads on SO related to it.

like image 24
therainmaker Avatar answered Nov 15 '22 04:11

therainmaker