Incorrect Multiple Cases in Switch not generating compiler error
This question already has an answer here:
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, ie 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.
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.
a, b
is a valid expression in both C and C++. It means "Evaluate a
, discard it, evaluate b
". The value of the expression is b
. So your original switch
has the following meaning:
variable = 1;
switch(variable)
{
case 2:
return 1;
case 4:
return 2;
default:
return 3;
}
For more on the comma operator, you can read the Wikipedia article.
链接地址: http://www.djcxy.com/p/84458.html上一篇: Switch语句中单个案例中的多重标准
下一篇: 开关中错误的多个案例不会产生编译器错误