Hello everyone,
I think printf %d works fine with signed, unsigned and negative integer values, and the same as %ld for long. Is that correct? If not, do we need to special conversion?
thanks in advance,
George
Printable View
Hello everyone,
I think printf %d works fine with signed, unsigned and negative integer values, and the same as %ld for long. Is that correct? If not, do we need to special conversion?
thanks in advance,
George
%d works for "normal length integer", whilst "%ld" is for "long" integers. Unsigned numbers should use "%u" or "%lu" depending on length. If you print a "large" unsigned with %d, then the result will be a negative number - which isn't what the unsigned number should be, since by definition, unsigned numbers are always positive. [Or, rather, they don't have a sign, if you want to represent only negative numbers, you could put a minus there yourself, but it's not got a "positive/negative" representation].
--
Mats
Where a normal integer is an int, and a long integer is a long int.Quote:
%d works for "normal length integer", whilst "%ld" is for "long" integers.
To answer your question, you're supposed to use %d for signed (or ordinary) ints, and %u for unsigned ints; %* for normal ints, and %l* for long ints.
If you don't specify a signed-ness, signed is the default. And if you don't say "long", then a normal sized int results.
These are all signed (%d):
These are unsigned (%u):Code:int x;
signed int x;
123;
These are long (%ld):Code:unsigned x;
unsigned int x;
123u;
These are unsigned long (%lu):Code:long x;
long int x;
123l;
123L;
Code:unsigned long x;
unsigned long int x;
123ul;
123UL;
123Lu;