Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c > #402429
| From | Tim Rentsch <tr.17687@z991.linuxsc.com> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: Dodging undefined behaviour in printf |
| Date | 2026-09-27 10:48 -0700 |
| Organization | A noiseless patient Spider |
| Message-ID | <86v77qr3ez.fsf@linuxsc.com> (permalink) |
| References | <119bf9d$1fk39$1@dont-email.me> |
highcrew <high.crew3868@fastmail.com> writes:
> Dear c.l.c.
>
> I'm trying to refine my knowledge on the topic of type promotions, and
> now I know how promotion is implied when passing arguments to a
> function whose prototype is missing argument definition, or to
> functions having variadic argument list.
>
> So I was wondering about the following:
>
> unsigned short x = value;
> printf("%x", x);
>
> Assuming that sizeof(unsigned short) < sizeof(int), I would guess that
> x is promoted to signed int, which is however the wrong type, as it
> should be unsigned int.
Yes, usually unsigned shorts are promoted to signed ints, although
the rule is expressed in terms of value ranges rather than sizes.
> Well, it is is also true that the `int` value is not going to be
> negative for sure.
>
> Would this be a problem? Am I supposed to explicitly cast x to
> (unsigned int) when passing it to printf?
The short answer is that just using 'x' works. No cast is
needed. For variadic arguments, corresponding signed and
unsigned types are interchangeable, as long as the argument
value is within the range of both types. The same rule applies
for arguments subject to the default promotions, if the function
being called is defined without a prototype.
> I find it interesting that the problem is not a problem on
> architectures where sizeof(unsigned short) == sizeof(unsigned int) --
> if I will ever find such a thing.
>
> How about %hx then?
How %hx works is the same as how %x works, except that whatever
value is sent (obtained as an unsigned int) is first converted
to unsigned short before formatting.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Dodging undefined behaviour in printf highcrew <high.crew3868@fastmail.com> - 2026-09-27 18:12 +0200 Re: Dodging undefined behaviour in printf Johann 'Myrkraverk' Oskarsson <johann@myrkraverk.invalid> - 2026-09-28 01:47 +0800 Re: Dodging undefined behaviour in printf Tim Rentsch <tr.17687@z991.linuxsc.com> - 2026-09-27 10:48 -0700 Re: Dodging undefined behaviour in printf James Kuyper <jameskuyper@alumni.caltech.edu> - 2026-09-27 20:30 -0400 Re: Dodging undefined behaviour in printf David Brown <david.brown@hesbynett.no> - 2026-09-28 09:50 +0200 Re: Dodging undefined behaviour in printf "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2026-09-30 13:05 -0700
csiph-web