当用大于 255 的整数分配 unsigned char 时,它会给出不同的输出,为什么?

when assigning the unsigned char with the integer greater than 255 it gives the different output , why?

#include<stdio.h>
int main()
{
   unsigned char c =292;
   printf("%d\n",c);
   return 0;
}  

以下代码给出输出“36”。 我想知道为什么会这样?

因为 292 不适合 unsigned char.

类型的变量

我建议你编译这个程序:

#include <stdio.h>
#include <limits.h>
int main()
{
   unsigned char c =292;
   printf("%d %d\n", c, UCHAR_MAX);
   return 0;
}

并检查输出:

prog.c: In function 'main':
prog.c:5:21: warning: unsigned conversion from 'int' to 'unsigned char' changes value from '292' to '36' [-Woverflow]
    unsigned char c =292;
                     ^~~
36 255

因此,UCHAR_MAX 在我的系统中是 255,这是您可以分配给 c 的最大值。

292 刚刚溢出 c,因为它是无符号类型,它从 0 到 255,因此它环绕,给你 292 - (255 + 1) = 36。

The size of char data_type is 1 byte and its range is 0 to 255. but here initialization is more than 255(i.e. c=292>255)

Hence, c stores (292-255)th value (i.e. 37th value) and the value c stores is 36(because 0 is the first value).

It means you have initialize c = 36.

And finally, printf() func. fetch value from memory and print the value 36.

当你将 292 转换为二进制时,你将得到 0001 0010 0100(9 位)。 但不幸的是,一个字符变量只能存储 1 个字节(8 位)。 所以它将占用最后 8 位。即:0010 0100 等于十进制的 36。 希望这有帮助