Am I allowed to use the NULL pointer as replacement for the value of 0?
No, it is not safe to do so. NULL
is a null-pointer constant, which could have type int
, but which more typically has type void *
(in C), or otherwise is not directly assignable to an int
(in C++ >= 11). Both languages allow pointers to be converted to integers, but they do not provide for such conversions to be performed implicitly (though some compilers provide that as an extension). Moreover, although it is common for converting a null pointer to an integer to yield the value 0, the standard does not guarantee that. If you want a constant with type int
and value 0 then spell it 0
.
- Am I might crossing into Undefined Behavior with this?
Yes, on any implementation where NULL
expands to a value with type void *
or any other not directly assignable to int
. The standard does not define the behavior of your assignment on such an implementation, ergo its behavior is undefined.
- is it permissible to operate with the NULL in that way?
It is poor style, and it will break on some systems and under some circumstances. Inasmuch as you appear to be using GCC, it would break in your own example if you compiled with the -Werror
option.
- Is there anything wrong about to use NULL as numerical value in arithmetical expressions?
Yes. It is not guaranteed to have a numerical value at all. If you mean 0 then write 0, which is not only well defined, but shorter and clearer.
- And how is the result in C++ to that case?
The C++ language is stricter about conversions than is C and has different rules for NULL
, but there, too, implementations may provide extensions. Again, if you mean 0 then that's what you should write.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…