验证C / C ++签署右移是算术特定的编译器? [英] Verifying that C / C++ signed right shift is arithmetic for a particular compiler?

查看:133
本文介绍了验证C / C ++签署右移是算术特定的编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C / C ++标准(见链接),该> >运营商C和C ++不一定是有符号数的算术移位。它是由编译器执行0的(逻辑)或符号位(算术)是否被移位在作为比特被移位到右边。

这会不会code函数在编译时刻发出(失败)为落实符号整数逻辑右移编译器?

 的#define COMPILE_TIME_ASSERT(EXP)\\
    的typedef INT CompileTimeAssertType ## __ __ LINE [(EXP)? 1:-1]#定义RIGHT_SHIFT_IS_ARITHMETIC \\
    ((((符号整数)-1)>> 1)==((符号整数)-1))// SHR必须算术使用此code
COMPILE_TIME_ASSERT(RIGHT_SHIFT_IS_ARITHMETIC);


解决方案

我看不错!您还可以设置编译器生成的汇编文件(或加载在调试器编译后的程序),并期待在其中运code它将为 INT签署我; I>> 1; ,但这不是自动喜欢你的解决方案

如果你发现没有实现有符号数的算术右移一个编译器,我想听听它。

According to the C / C++ standard (see this link), the >> operator in C and C++ is not necessarily an arithmetic shift for signed numbers. It is up to the compiler implementation whether 0's (logical) or the sign bit (arithmetic) are shifted in as bits are shifted to the right.

Will this code function to ASSERT (fail) at compile time for compilers that implement a logical right shift for signed integers ?

#define COMPILE_TIME_ASSERT(EXP) \
    typedef int CompileTimeAssertType##__LINE__[(EXP) ? 1 : -1]

#define RIGHT_SHIFT_IS_ARITHMETIC \
    ( (((signed int)-1)>>1) == ((signed int)-1) )

// SHR must be arithmetic to use this code
COMPILE_TIME_ASSERT( RIGHT_SHIFT_IS_ARITHMETIC );

解决方案

Looks good to me! You can also set the compiler to emit an assembly file (or load the compiled program in the debugger) and look at which opcode it emits for signed int i; i >> 1;, but that's not automatic like your solution.

If you ever find a compiler that does not implement arithmetic right shift of a signed number, I'd like to hear about it.

这篇关于验证C / C ++签署右移是算术特定的编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆