【发布时间】:2010-09-29 15:20:18
【问题描述】:
这是一个奇怪的...
我正在玩一些减压算法。我没有通过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;
}
};
不考虑 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
我错过了什么?
提前致谢
【问题讨论】:
-
联合声明后的冒号是有意的吗?
-
您的错误指出了原因。 uMask1 应替换为您需要检查的常量数据,而不是 uMask1。
标签: c++ compiler-errors switch-statement