Bitwise Leftshift (<<) strange behavior

后端 未结 6 948
鱼传尺愫
鱼传尺愫 2021-01-15 13:41

gcc bitwise Leftshift (<<) strange behavior. Here is my code:

#include 
#include 

void foo(in         


        
6条回答
  •  渐次进展
    2021-01-15 14:06

    According to the C standard ISO 9899:1999 Chapter 6.5.7 Bitwise shift operators:

    The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

    It is strange that the compiler treats the two expressions differently. But since this causes undefined behavior anyway, it's not a problem. What you need to do is to check the operands before evaluation to make sure it's a valid expression.

提交回复
热议问题