C++ Logo

std-proposals

Advanced search

[std-proposals] Fwd: Type-safe printf and auto

From: Alejandro Colomar <alx.manpages_at_[hidden]>
Date: Sun, 12 Mar 2023 22:57:16 +0100
[Resending from my other address, from which I'm subscribed]


-------- Forwarded Message --------
Subject: Re: [std-proposals] Type-safe printf and auto
Date: Sun, 12 Mar 2023 22:55:19 +0100
From: Alejandro Colomar <alx.manpages_at_[hidden]>
To: Robin Rowe <robin.rowe_at_[hidden]>, std-proposals_at_[hidden]

Hi Robin,

On 3/12/23 22:08, Robin Rowe wrote:
> > For printing the value, whatever the type is, you should use "%jd" and
> > cast the value to (intmax_t).
>
> Thank you, Alejandro. You are right of course that a cast can silence a
> type warning.
>
> Sometimes I do cast the printf arg like you suggest, but to (int), not
> bothering with intmax_t. Narrowing legacy code variables that work fine
> in 32-bit is unlikely to cause trouble. While I've often done that, and
> used stringize macros too as you suggested, I would prefer a general
> solution that is elegant.
> Appreciate all feedback.

 printf("Var %s is of type %s and has value %i\n",
        STRINGIFY(x), TYPESTR(x), (int) x);

I think this is rather elegant. I don't think something you can
standardize could be better. Especially, since you'd need to be
compatible with C.

The implementation of STRINGIFY() and TYPESTR() can be as ugly as
it needs to be, since you only write it once. The important part
is usability, and I don't think the printf(3) call above is ugly
or inelegant.

Cheers,

Alex

>
> Robin

-- 
<http://www.alejandro-colomar.es/>
GPG key fingerprint: A9348594CE31283A826FBDD8D57633D441E25BB5

Received on 2023-03-12 21:57:19