glo*_*fer 6 c++ compiler-errors switch-statement
这是一个奇怪的...
我正在玩一些减压算法.char buffer[]
在buffer[i]
找到停止位之前,我没有经过和循环 ,而是尝试使用一些位掩码技术但是使用字符.
我有以下示例:
// In a *.h file
const char ch = '\x81';
// To avoid Endianess
union CharUInt
{
char sz[4];
unsigned int u;
};
// Legal because char[] is declared before uint32 in the union
const CharUInt Mask1 = {'\x81', '\x0', '\x0', '\x81'};
const CharUInt Mask2 = {'\x0', '\x81', '\x81', '\x0'};
// Proxy / Auxillary uint32 as usimg Mask2.u in the switch blocked produced the same errors
const unsigned int uMask1 = Mask1.u;
const unsigned int uMask2 = Mask2.u;
const unsigned int uMask_ = (uMask1 & uMask2);
// buf is always long enough
bool Foo(char buf[])
{
const CharUInt Type = {buf[0], buf[1], buf[2], buf[3]};
unsigned int uType = (Type.u & uMask_);
switch(uType)
{
case uMask1:
// do stuff
case uMask2:
// do more stuff
return true;
break;
default:
// do different stuff
return false;
break;
}
};
Run Code Online (Sandbox Code Playgroud)
不考虑union
东西的语法(实际代码编译运行正常)并且不考虑函数返回Foo
是否漂亮,我得到
'uMask1' cannot appear in a constant-expression
并且如果使用了联合本身,我得到
'Mask1' cannot appear in a constant-expression
'.' cannot appear in a constant-expression
并且当然错误也适用于uMask2和Mask2.u
我错过了什么?
提前致谢
混淆来自const和const是两个的事实.
switch语句中的case需要'常量表达式'.或者换句话说:编译器可以在编译时"计算"的表达式.这可能是一个硬编码的数字(如42),或者之前已经定义为数字的东西(使用#define).
编译器也使用Const,其含义是"一旦此变量具有值,它将不再更改".例如,在以下代码中:
void myFunction (const int value)
{
...
}
Run Code Online (Sandbox Code Playgroud)
值将是常量.我将无法更改const的值,但这并不会使它成为编译器的"常量表达式".
在你的情况下,uMask1是const(不能再改变它)但不是常量表达式.