Leonardo
Leonardo

Reputation: 1522

If unsigned types should not have negative values, why is it negative when I turn on all the bits?

#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;
}

I am using CodeBlocks12.11, and MinGW 4.7.0-1 on Windows 7. And for some reason I am having trouble making my variable x acquire the largest possible decimal value representation. Why does this happen, I am sure that x = ULONG_MAX should work but it also results in -1, now surely that is not right! I tried compiling it outside of Code-Blocks as well.

What am I missing here?

Upvotes: 1

Views: 95

Answers (1)

user1944441
user1944441

Reputation:

You have to print unsigned variables with u. A long is prefixed with l, hence you need lu in this case.

printf("%lu\n", x);

Upvotes: 9

Related Questions