1
#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?

2
  • 1
    Turn on compiler warnings. Commented Mar 30, 2013 at 0:40
  • Yes, as @Zoidberg says, the compiler's warning would have pointed out your mistake right away. Commented Mar 30, 2013 at 3:15

1 Answer 1

9

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);
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you, I knew it would be something terribly obvious!
@PascalCuoq Tnx made a typo.
Isn't that supposed to be %lu?
@Armin I didn't downvote, but that's not correct. It's possible for unsigned long to be larger than unsigned. It might not be on your system, but the standard allows it.
@Leonardo turn on compiler warnings and listen to them. Any modern compiler will complain when the format specifiers do not match the types. You must not use the wrong specifier since that will (and should) undoubtedly break sometime.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.