c - 切换数据类型 int 的第 100 位会产生意想不到的结果

标签 c gcc int bit-manipulation toggle

下面的代码只是请求一个数字 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/

相关文章:

C-Python asyncio : running discord. py 在线程中

java - 实现固定大小的 HashMap

c - 如何使用指针初始化结构?

c - 如何在 C 的共享库中使用外部符号

c - Anagrams - 在 C 中使用链接和探测进行散列

c - 如何在代码块中向编译器添加标志?

c - 为什么 GCC 9.1.0 有时会提示这种 strncpy() 的使用?

java - 为什么我的应用程序在我单击某个按钮时崩溃?

c++ - 将 int16_t 转换为 uint_8t*

c++ - 如何用 C++ 中的整数替换 char 数组中的某些项?