views:

339

answers:

4

I can never understand how to print unsigned long datatype in C.

Suppose boo is an unsigned long, then I try:

  • printf("%lu\n", unsigned_boo)
  • printf("%du\n", unsigned_boo)
  • printf("%ud\n", unsigned_boo)
  • printf("%ll\n", unsigned_boo)
  • printf("%ld\n", unsigned_boo)
  • printf("%dl\n", unsigned_boo)

And all of them print some kind of -123123123 number instead of unsigned long that I have.

I can't figure it out, can you help me?

Thanks, Boda Cydo.

+11  A: 

%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?

Thanatos
Oops, `%lu` worked this time. Thanks. Something else must have happened before and it didn't work.
bodacydo
@bodacydo: If you've got a bug, it might appear at semi-random... make sure your variable has a valid value before you try printing it.
Thanatos
Even if the variable is uninitialized, there should be no way printf reaches a point where it could print a minus sign when the format specifier was `%lu`. Technically it's undefined behavior but in reality the variable has an unpredictable value that gets passed to printf which printf then interprets as unsigned. I'm guessing bodacydo's original problem was flow reaching an incorrect printf call instead of the one intended...
R..
+1  A: 

The correct specifier for unsigned long is %lu.

If you are not getting exact value you are having then there may be some problem in your code.

Please copy your code here.Then may be someone can tell you better what is the problem.

Thanks

Alok.Kr.

Kumar Alok
+2  A: 

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

R..
A: 

The format is %lu.

Please check about the various other datatypes and their usage in printf here

Praveen S
Various nonstandard behavior is documented there without marking it as nonstandard. POSIX is the easiest-to-access online standard for printf; extensions beyond ISO C are marked with the "CX" tag:http://www.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
R..
Thanks mate!! I will consider that.
Praveen S