编译器如何识别字节移位运算符的长度

考虑以下行:

int mask = 1 << shift_amount;

我们知道这mask是 4 个字节,因为它是明确声明的int,但是1要移动的这个长度未知。如果编译器选择 type 为char8 位,或者它的unsigned short大小可能为16 位,那么移位结果实际上将取决于编译器关于如何处理它的决定的大小1。编译器在这里如何决定?以这种方式保留代码是否安全,或者应该改为:

int flag = 1;

int mask = flag << shift_amount;

回答

1是一个int(通常为 4 个字节)。如果您希望它不是int使用后缀的类型,例如1Lfor long。有关更多详细信息,请参阅https://en.cppreference.com/w/cpp/language/integer_literal。

您也可以使用演员表,(long)1或者如果您想要一个已知的固定长度,(int32_t)1.

正如 Eric Postpischil 在评论中指出的那样,小于intlike 的值(short)1没有用,因为无论如何<<都会提升左侧的参数int

  • `(short)1` will not “work” to make the shift act on less than an `int`; the left operand of `<<` is always promoted to at least `int`.

以上是编译器如何识别字节移位运算符的长度的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>