On 24.02.2020 23:35, Mouse wrote:
>> Unless I remember wrong, older C standards explicitly say that the
>> integer 0 can be converted to a pointer, and that will be the NULL
>> pointer, and a NULL pointer cast as an integer shall give the value
>> 0.
>
> The only one I have anything close to a copy of is C99, for which I
> have a very late draft.
>
> Based on that:
>
> You are not quite correct. Any integer may be converted to a pointer,
> and any pointer may be converted to an integer - but the mapping is
> entirely implementation-dependent, except in the integer->pointer
> direction when the integer is a "null pointer constant", defined as
> "[a]n integer constant expression with the value 0" (or such an
> expression cast to void *, though not if we're talking specifically
> about integers), in which case "the resulting pointer, called a null
> pointer, is guaranteed to compare unequal to a pointer to any object or
> function". You could have meant that, but what you wrote could also be
> taken as applying to the _run-time_ integer value 0, which C99's
> promise does not apply to. (Quotes are from 6.3.2.3.)
>
> I don't think there is any promise that converting a null pointer of
> any type back to an integer will necessarily produce a zero integer.
>
> /~\ The ASCII Mouse
> \ / Ribbon Campaign
> X Against HTML mouse%rodents-montreal.org@localhost
> / \ Email! 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B
>
$ cat test.cpp
#include <cstddef>
int
main(int argc, char **argv)
{
if (((char *)0)[argc])
return 1;
else
return 0;
}
$ g++ test.cpp
$ ./a.out
Memory fault (core dumped)
And some variations:
$ g++ test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:6:15: warning: converting NULL to non-pointer type
[-Wconversion-null]
if (NULL[argc])
^
test.cpp:6:15: error: invalid types ‘long int[int]’ for array subscript
$ g++ test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:6:18: error: invalid types ‘std::nullptr_t[int]’ for array
subscript
if (nullptr[argc])
^
NULL in C is expected to be harmonized with nullptr from C++.
We still can store NULL/nullptr in variables as before and there is no
change in the produced code. The only change is on the syntax level as
we can catch more bugs earlier. Whenever a compiler will be smart enough
to deduce that the code is nullptr[0] it will raise an error.
Attachment:
signature.asc
Description: OpenPGP digital signature