C++ Logo

std-proposals

Advanced search

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

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Mon, 13 Mar 2023 02:26:20 +0200
On Mon, 13 Mar 2023 at 02:05, Robin Rowe via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> > What makes you think that it's a small change to printf?
>
> Am basing my thinking on the fact that modern C compilers warn on type
> mismatch in printf, even say what the type is and what the right flag
> would be.

Well, the problem there is that the compiler knows that the format
string is a compile-time constant, but the
implementation of printf doesn't. And the compiler knows the types of
the arguments passed that correspond
to the format string, and can see mismatches, but the implementation
of printf doesn't. There's no mechanisms
for those things in C, yet. Some C compilers expose the knowledge of
whether the format string is a constant
to the implementation of printf, but others don't. And none of them
expose the knowledge of the types of the arguments
passed in.

In C++, the situation is different - you have language mechanisms
where the argument types are retained to be visible
to the implementation (they can be deduced function arguments, for
instance), and there are language mechanisms
that ensure that a format string is always a constant (its constructor
is consteval).

In other words, in C++, there are mechanisms that allow you, the
normal programmer, to write a formatted-printing
function that verifies at compile-time that a format string matches
the types of the arguments given. In C, you don't
have those mechanisms. In C++, you can write that function portably.
In C, you need to resort to non-portable
mechanisms, which might not even be there at all.

Hence the skepticism that it's a small change to a function that must
exist in C.

Received on 2023-03-13 00:26:33