I can never understand how to print unsigned long
datatype in C.
Suppose unsigned_foo
is an unsigned long
, then I try:
printf("%lu\n", unsigned_foo)
printf("%du\n", unsigned_foo)
printf("%ud\n", unsigned_foo)
printf("%ll\n", unsigned_foo)
printf("%ld\n", unsigned_foo)
printf("%dl\n", unsigned_foo)
And all of them print some kind of -123123123
number instead of unsigned long
that I have.
%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?
For int %d
For long int %ld
For long long int %lld
For unsigned long long int %llu
%lu for unsigned long
%llu for unsigned long long
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
).
printf
is specified to require the exact correct argument types without the allowances that va_arg
would have.
int main()
{
unsigned long long d;
scanf("%llu",&d);
printf("%llu",d);
getch();
}
This will be helpful . . .
The format is %lu
.
Please check about the various other datatypes and their usage in printf here
The correct specifier for unsigned long is %lu
.
If you are not getting the exact value you are expecting then there may be some problems in your code.
Please copy your code here. Then maybe someone can tell you better what the problem is.
Success story sharing
%lu
worked this time. Thanks. Something else must have happened before and it didn't work.%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...%lu
, broken out is:%
— starts a "conversion specification";l
— the length modifier,l
means "[unsigned] long int";u
— the conversion specifier,u
is for anunsigned int
to be printed out as decimal. Because we gave the length modifierl
, it then accepts anunsigned long int
. The letters must be in that order: percent, length, conversion. (There are a few more options, such as width and precision, that you can add. See the man page, as it documents all this precisely!)