Some code.cpp file contains
extern const int v1;
extern const int v2;
extern const int v3;
extern const int v4;
int _tmain(int argc, _TCHAR* argv[])
{
int aee = v1;
switch (aee)
{
case v1:
break;
case v2:
break;
case v3:
break;
case v4:
break;
}
return
}
Another file definition.cpp contains
const int v1 = 1;
const int v2 = 2;
const int v3 = 3;
const int v4 = 4;
When I do compile I got error C2051: case expression not constant However when I remove extern everything is just fine.
Is there any way to make it work with extern?
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
getchar() and putchar() getchar() reads a single character from standard input (there is a version getc(file) to read from a file).
No. switch
only works with fully defined integral type constants (including enum members and classes that unambiguously cast to integral type). here is a link to an old reference of MSDN, but what is says is still valid.
This link that I provided in a comment to another answer explains what optimizations compilers may perform to assembly code. If this was delayed to the linking step, it would not be easily possible.
You should therefore use if
..else if
in your case.
Switch statements requires that the case values are known at compile time.
The reason why it seems to work when you remove the extern
is that you define a constant zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With