Path: csiph.com!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: #include
Date: Thu, 24 Jun 2021 10:31:37 -0700
Organization: A noiseless patient Spider
Lines: 51
Message-ID: <86bl7vb24m.fsf@linuxsc.com>
References: <87wnqxxoe3.fsf@nosuchdomain.example.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="5f9785b3afd09fb507884e20b2dfc5bb"; logging-data="11437"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19Z2NAnEVKIf1zb2D1smHuyXagsppHCXY0="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:aUiYSCRCweQffHiEGaJVD8pxgaE= sha1:g+rM6cgGnPFeIpqQsA/Y6YU8FSE=
Xref: csiph.com comp.lang.c:161482
Keith Thompson writes:
[... on printing various integer types ...]
> Using the macros:
>
> #include
> // #include
> #include
> #include
>
> int main(void) {
> printf("INT_MAX : %d\n", INT_MAX);
> printf("INT_MIN : %d\n", INT_MIN);
> printf("LONG_MAX : %ld\n", LONG_MAX);
> printf("LONG_MIN : %ld\n", LONG_MIN);
> printf("UINT_MAX : %u\n", UINT_MAX);
> printf("ULONG_MAX : %lu\n", ULONG_MAX);
> printf("USHRT_MAX : %u\n", (unsigned)USHRT_MAX);
The cast in the last line is not needed.
> printf("\nFrom stdint.h: \n");
> printf("INT8_MAX : %" PRId8 "\n", INT8_MAX);
> printf("INT16_MAX : %" PRId16 "\n", INT16_MAX);
> printf("INT32_MAX : %" PRId32 "\n", INT32_MAX);
> printf("INT64_MAX : %" PRId64 "\n", INT64_MAX);
> printf("UINT8_MAX : %" PRIu8 "\n", UINT16_MAX);
> printf("UINT16_MAX : %" PRIu16 "\n", UINT16_MAX);
> printf("UINT32_MAX : %" PRIu32 "\n", UINT32_MAX);
> printf("UINT64_MAX : %" PRIu64 "\n", UINT64_MAX);
> }
>
> Most of the casts in your original program are unnecessary, since
> the expressions are already of the type you were casting them to.
> But unsigned short could promote either to signed int or to
> unsigned int, depending on their ranges, so converting to unsigned
> and using "%u" is appropriate. In general, when passed to a
> variadic function like printf, an argument of an integer type
> narrower than int is promoted to int if type's range fits in int,
> to unsigned int otherwise.
The description of how type promotion works is right, however a
cast is still not needed there. The reason is that values given
as variadic arguments are allowed to be the corresponding signed
or unsigned version of the type used to get the value, and that
will work as long as the value is in the set of values common to
both types. If an unsigned short promotes to int, then its value
is guaranteed to be in the set of values representable by both
int and unsigned int, and hence using %u for an uncasted unsigned
short is always safe.