Unicorn
Unicorn

Reputation: 1417

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?

Upvotes: 12

Views: 2373

Answers (2)

Benoit
Benoit

Reputation: 79235

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.

Upvotes: 9

Lindydancer
Lindydancer

Reputation: 26134

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.

Upvotes: 3

Related Questions