下面的代码只是请求一个数字 num
然后是那个数字的一点 tbit
来切换/反转然后打印新数字 ans
。
在带有 gcc 编译器版本 6.3.0 20170516 的 debian 9 上使用 Geany,当我执行以下代码时,我得到的答案 ans
为 6,而我本以为会提示编译器或运行时错误我我越界了。
使用此版本的 gcc,sizeof(int)
返回四个字节或 32 位。当我尝试切换第 100 位时,发生了什么 ans=6
?
示例输入:
Enter a number : 22
Enter the bit you want to toggle : 100
输出:
The number you entered is 22
after toggling the 100 bit
the new number is 6.`
代码:
#include <stdio.h>
int main ()
{
int num, tbit, tool = 1, ans;
printf(Enter a number :");
scanf("%d", &num);
printf(Enter the bit you want to toggle :");
scanf("%d", &tbit);
ans = (tool<<tbit) ^ num;
printf("The number you entered is %d after toggling the %d bit the new
number is %d\n" , num, tbit, ans);
return 0;
}
最佳答案
C 没有“运行时错误”这样的东西。在表达式 x<<n
中,如果 n
的值超过了 x
的(提升的)类型的宽度,或者如果类型已签名并且结果会溢出,则行为未定义。这意味着该语言不会对发生的事情强加任何要求,而且它可能是奇怪和意外的事情。
相关文本是6.5.7 位移运算符,¶3:
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.
关于c - 切换数据类型 int 的第 100 位会产生意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955862/