c - 左操作数为负时的未定义行为

标签 c bit-shift

几天前,我参加了 Microsoft GD 在线考试,在那里实习。我一直在研究负数的左移是一种未定义的行为,但那篇论文有 30 个问题中有近 7 个与移位运算符有关,大约 5 个问题涉及将负数向左移动,他们没有选择说“未定义”行为”。看到那个我很震惊。所以,我的问题是这个 C 标准改变了吗?现在定义了吗? 示例问题:

printf("%d",-1<<10);

I marked its answer as -1024 by the logic 2^10*-1

我什至在 gcc 上运行它,它只给了我 o/p 为 -1024(当我回到家时。)

最佳答案

规则没有改变。它在技术上仍未定义。

引用自 C 标准(n1548 第 6.5.7 节,第 4 段):

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

它清楚地表明,如果 E1 不是无符号的或带有非负值的符号,则行为未定义。

关于c - 左操作数为负时的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13411748/

相关文章:

c++ - 系统日志不转发远程消息

PHP 等效的 javascript >>> 使用零填充按位运算符右移?

c++ - 尝试编写一个 C++ 函数来对 8 位字符进行非十六进制编码并将其转换为整数

将 int 转换为 uint8_t 数组十六进制值

c - 从 'int' 到 'FILE*' 的转换无效

c - 运行时检查失败 #2 - 变量 'command' 周围的堆栈已损坏

c - GLSL Shader 编译失败,没有错误消息

c++ - GTK+ 下拉菜单到工具栏项

c - 按位移位说明

java - 位移位操作不返回预期结果