如果无符号类型不应该有负值,为什么当我打开所有位时它是否定的?

Leo*_*rdo 1 c limit

#include <stdio.h>
#include <math.h>
#include <limits.h>

int main(void)
{
    unsigned long x = 0;

    x = x ^ ~x;
    printf("%d\n", x);

    x = (unsigned long)pow(2, sizeof(x)*8);
    printf("%d\n", x);

    x = ULONG_MAX;
    printf("%d\n", x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在Windows 7上使用CodeBlocks12.11和MinGW 4.7.0-1.由于某种原因,我无法使我的变量x获得最大可能的十进制值表示.为什么会发生这种情况,我相信它x = ULONG_MAX应该有效,但它也会产生-1,现在肯定是不对的!我也尝试在Code-Blocks之外编译它.

我在这里错过了什么?

小智 9

您必须使用打印无符号变量u.长的是前缀l,因此lu在这种情况下你需要.

printf("%lu\n", x);
Run Code Online (Sandbox Code Playgroud)

  • 那不应该是`%lu`吗? (4认同)
  • @Armin我没有downvote,但那不正确.`unsigned long`可能比`unsigned`大.它可能不在您的系统上,但标准允许它. (2认同)