在C中存储变量

Mat*_*ian 0 c variables int types char

我在C语言中遇到了一些基本概念的挑战.帮助将非常有用.我继续用代码的解释注释代码以及我试图在那里问的问题.

void main (void)
{
  printf("%x", (unsigned)((char) (0x0FF))); //I want to store just 0xFF;
  /* Purpose of the next if-statement is to check if the unsigned char which is 255
   * be the same as the unsigned int which is also 255. How come the console doesn't print
   * out "sup"? Ideally it is supposed to print "sup" since 0xFF==0x000000FF.
   */
  if(((unsigned)(char) (0x0FF))==((int)(0x000000FF))) 
     printf("%s","sup");
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助.

Dan*_*her 8

你的括号错了,

if(((unsigned)(char) (0x0FF))==((int)(0x000000FF))) 
Run Code Online (Sandbox Code Playgroud)

在左操作数上执行两次强制转换,首先是char,通常(1)得到-1,然后该值被强制转换为unsigned int,通常为(2),结果为2 ^ 32-1 = 4294967295.

(1)如果char是有符号的,则使用8位宽,使用2的补码,并且仅通过取最低有效字节来完成转换,就像大多数托管实现的情况一样.如果char是无符号或宽于8位,则结果为255.

(2)如果转换char为-1导致unsigned int为32位宽.

  • "正确"版本:`(unsigned char)0xFF` (7认同)