如何将 switch 与外部常量一起使用?
一些 code.cpp 文件包含
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
}
另一个文件定义.cpp 包含
const int v1 = 1;
const int v2 = 2;
const int v3 = 3;
const int v4 = 4;
当我编译时,出现错误 C2051:大小写表达式不恒定 但是,当我删除 extern 时,一切都很好。
有什么办法让它与 extern 一起工作吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以。switch 仅适用于完全定义的整型常量(包括明确转换为整型的枚举成员和类)。 这里是 MSDN 旧参考的链接,但是所说的话仍然有效。
我在另一个答案的评论中提供的此链接解释了编译器可以对汇编代码执行哪些优化。如果这延迟到链接步骤,就不容易实现了。
因此,您应该在您的情况下使用
if
..else if
。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 语句要求在编译时已知 case 值。
当您删除
extern
时它似乎起作用的原因是您定义了一个常量零。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.