Re: Printf question.



Keith Thompson wrote:
Jack Klein <jackklein@xxxxxxxxxxx> writes:
On 30 Dec 2005 11:21:25 -0800, "praeiji" <spacecaps@xxxxxxxxx> wrote
in comp.lang.c:
[...]
unsigned char a = 200;
char b = 200;
printf( "%d %d", a, b );

gives :

200, -56

How comes? I didn't tell printf that the first argument was unsigned
and it detected it on its own. It doesn't seem possible with varargs.
How is it possible?
[snip]

In the case of integer types of lesser rank than int, the "integer
promotions" occur.  Since a signed int can hold the value 200, the
value in the unsigned char 'a' is converted to the int value 200.

Correction: since a signed int can hold any value of type unsigned char, the value in the unsigned char 'a' is promoted to type int.

<annoying pedant> What, even on a system with CHAR_BIT==16 and sizeof(int)==1 ? </annoying pedant>

Of course, you are only likely to find such systems in the embedded world where you may well not have printf.

> The
promoted type doesn't depend on the value that happens to be in the
variable; it depends on which type can hold *any* possible value of
the type.

You are, of course, correct that is is purely a matter of type, not the value the variable happens to contain.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
.




Relevant Pages

  • Re: printf
    ... At the end is a very basic printf (for instance no ... int m_fprintf (FILE *stream, const char fmt, ...); ... fmax = 0; ...
    (comp.lang.c)
  • Re: Strange behaviour
    ... Undefined behaviour -- %X expects an unsigned int, ... pass it a char. ... An int is passed. ... the integer promotions are performed on each argument, ...
    (comp.lang.c)
  • [EXPL] MySQL MaxDB Webtool Buffer Overflow Exploit (%)
    ... int exploit; ... int shell (int s, char* tip, unsigned short cbport); ... printf; ... exit; ...
    (Securiteam)
  • Re: how the following two code parts same
    ... mainreturns int by definition. ... char i = NULL; ... to zero. ... printf; ...
    (comp.lang.c)
  • Re: Strange behaviour
    ... pass it a char. ... the integer promotions are performed on each argument, ... a char is a type of int. ... char is an integer type; ...
    (comp.lang.c)