Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is &*NULL well-defined in C++?

In what version(s) of the C++ standards (if any) is the following well-defined?

void foo(void) {
    char *nullPtr = NULL;
    &*nullPtr;
}

Note that I am specifically asking about &*nullPtr here. I am aware that simply *nullPtr is undefined - but this is a separate question and hence the currently-linked "duplicate" is not a duplicate.

Note that I am not assigning the result to anything - the second line is a simple statement.

This should be a question with an obvious answer, but (as seemingly happens way too often on such questions) I have heard just as many people say the answer is "obviously undefined" as "obviously defined".

On a rather related note, what about the following? Should foo produce a read of c?

extern volatile char c;

void bar(void) {
    volatile char *nonnullptr = &c;
    &*nonnullptr;
}

(C version of the same question: Is &*NULL well-defined in C?)

like image 734
TLW Avatar asked Aug 05 '18 04:08

TLW


1 Answers

This is four questions in one.


&*nullPtr is well-defined in C since C99, which says of the unary & operator:

If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, [...]

See WG14 N721 and DR076.


&*nullPtr is formally undefined in all revisions of C++ (by omission: unary & is specified to produce a pointer to "the designated object", and unary * is specified to produce "an lvalue referring to the object [...] to which the expression points"; a null pointer value points to no object), although the direction of core issue 232 is to make this well-defined.


&*nonnullptr produces no volatile read of *nonnullptr. Unary & expects an lvalue operand; no lvalue conversion (for C) or lvalue-to-rvalue conversion (for C++) is performed for *nonnullptr.

like image 106
T.C. Avatar answered Oct 05 '22 12:10

T.C.