C++ Logo

std-proposals

Advanced search

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

From: Alejandro Colomar <alx.manpages_at_[hidden]>
Date: Mon, 13 Mar 2023 13:33:36 +0100
[forwarding, due to my other email not being subscribed]


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



On 3/13/23 03:02, Robin Rowe wrote:
>> No, that's not silencing a warning. That's fixing the bug. That's one
>> of the few places where a cast is the right thing.
>
> Interesting idea, Alex. However, I don't think so. Doing a cast is
> always taking a chance of unexpected results.

As a curiosity, there's a place where adding a cast can improve type
safety, rather than decrease it: malloc(3).

While I'm against manually casting the result of malloc(3), as
<https://stackoverflow.com/a/605858/6872717> suggests, there are
benefits if you cast the result of malloc(3), as
<https://stackoverflow.com/a/14879184/6872717> suggests. So, you can
automate the cast in a macro, as done here:

<https://github.com/shadow-maint/shadow/commit/6e58c1275252f3314d1aa5cc4d7e7f9068e3a902>

Something interesting to pick from there is that maybe you can write
a function to do the type conversion without having to do a cast. I'm
not sure if it's worth a function (or macro), but if you use it
frequently, it might be reasonable:

    inline intmax_t ji(intmax_t ji)
    {
        return ji;
    }

Then, use it as:

    foo_t x = 3;

    printf("%ji\n", ji(x));

Whatever foo_t evaluates to, as long as it's an integral type, the
above will be correct. No casts involved.

Cheers,

Alex

> I typically fix printf
> warnings by changing the format to use the right flag.
>
> Just a thought, if casting to (intmax_t) is always the right thing, then
> printf would only need one integer format flag... ;-)
>
> Appreciate the feedback.
>
> Robin
>

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

Received on 2023-03-13 12:33:39