几天前,我参加了 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/