【发布时间】:2011-11-01 05:38:12
【问题描述】:
可能重复:
Macro to test whether an integer type is signed or unsigned
为了测试给定的整数类型是有符号还是无符号,我使用了以下宏:
#define IS_SIGNED(type) ((type)~0 < 0)
int main()
{
if(IS_SIGNED(char))
cout<<"The char type is signed"<<endl;
if(IS_SIGNED(unsigned char))
cout<<"The unsigned char type is signed"<<endl;
}
该程序将在使用二进制补码表示的实现中运行。这个想法是当零是一个补码时,MSB 将设置为 1。然后根据类型转换,结果将是正数或负数。
我想知道您对这个关于可移植性的宏定义的看法?
【问题讨论】:
-
我对它的便携性没有什么疑虑;我只是不清楚它什么时候有用。
-
@JonathanLeffler - 在另一个宏内部,它以整数类型作为参数,根据符号来控制代码输出。
-
@R..:
~0在什么情况下会导致崩溃? -
它可以是不带负零的补码实现上的陷阱表示。
标签: c