C++ Logo


Advanced search

Re: [wg14/wg21 liaison] nullptr + 0

From: JeanHeyd Meneide <phdofthehouse_at_[hidden]>
Date: Thu, 26 Oct 2023 08:59:54 -0400
On Thu, Oct 26, 2023 at 8:41 AM Jens Maurer via Liaison <
liaison_at_[hidden]> wrote:

> On 26/10/2023 14.29, Robert Seacord via Liaison wrote:
> >
> > Does anyone know why |nullptr + 0| is defined in C++ but not C?
> What makes you believe "nullptr + 0" to be well-formed in C++?
> At least two compilers (gcc, clang) agree it's not:
> x.cc:4:22: error: invalid operands of types ‘std::nullptr_t’ and ‘int’ to
> binary ‘operator+’
> 4 | void * p = nullptr + 0;
> | ~~~~~~~~^~~

Having had this conversation in C before, I'm going to presume he means not
the literal null pointer but the clause in [expr.add] ¶4.1 that explicits
exempts it from undefined behavior when used on any pointer whose value is
the null pointer with 0:

When an expression J that has integral type is added to or subtracted from
an expression P of pointer type, the result has the type of P:
— If P evaluates to a null pointer value and J evaluates to 0, the result
is a null pointer value.

     This is indeed different from C, where there is no carve out for this
case in particular.


Received on 2023-10-26 13:00:08