Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use switch with extern constants?

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?

like image 575
Unicorn Avatar asked Apr 07 '11 09:04

Unicorn


People also ask

Can we use constants in switch case?

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.

Which function is read input from switch?

getchar() and putchar() getchar() reads a single character from standard input (there is a version getc(file) to read from a file).


2 Answers

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.

like image 161
Benoit Avatar answered Sep 21 '22 02:09

Benoit


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.

like image 25
Lindydancer Avatar answered Sep 21 '22 02:09

Lindydancer