This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: printf format specifiers
- From: Segher Boessenkool <segher at koffie dot nl>
- To: Steve Dondley <s at dondley dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Tue, 22 Oct 2002 15:04:47 +0200
- Subject: Re: printf format specifiers
- References: <FAECKOGIHAIBBPKBOKGNIEFADOAA.s@dondley.com>
Hi Steve,
> I have the following line in one of my programs:
>
> printf("%d\n", *string);
>
> *string is a pointer to a string. The above line prints out the ASCII
> decimal equivalent of the character that the pointer is pointing to. This
> is what I was looking to accomplish.
>
> My question is why? Why wouldn't I need to use the %hu (unsigned short
> integer) format specifier? When I do use the %hu, I get precisely the same
> results. This despite the fact that %d reads an entire word and %hu reads a
> single byte.
>
> Is this some compiler magic going on here?
printf() is declared something like
int printf(const char *format, ...);
The ellipsis (dots) here means the function takes "variable arguments".
All arguments passed "through the ellipsis" are subject to the default integer
conversions:
- if all values representable by the type of the argument are representable
by the type "int", the argument is converted to "int";
- otherwise, if all values representable by the type of the argument are
representable by the type "unsigned int", the argument is converted to
"unsigned int";
- otherwise, the argument is passed as-is.
In your case, "string" is a pointer to char, so *string is a char, which matches
the first case above, so it is passed as int, so the format specifier "%d" works
just fine. If you use "%hu", printf() still reads an int, but converts it to
an unsigned short. Now either you didn't test this with negative char values,
or your char happens to be an unsigned type; otherwise, "%hu" wouldn't have
given the same output as "%d".
Btw, if you wanted to print it as a char value, instead of a short value, you
should have used "%hhd" or "%hhu".
Hope this clarifies things for you,
Segher