3 ms·
This is where I get a bit lost in the spec, I think... Can the compiler know that the value of `i` is 0? If yes, then the spec says regardless of how the imple
by shadowgovt 2y ago
This is where I get a bit lost in the spec, I think... Can the compiler know that the value of `i` is 0?
If yes, then the spec says regardless of how the implementation defines nullptr, assigning literal 0 to a pointer variable is assigning a nullptr (i.e. the compiler must turn `0` into whatever the nullptr is in the underlying implementation).
If no, then 0 is just some unknown value and the assignment gives you an implementation-dependent (not necessarily invalid) pointer to whatever address `0` means on this architecture.
- int_19h 2y agoThe C spec only requires that integer constant expressions that have zero value are nullptrs. The moment you assign it to an int variable, it's no longer a constant expression as far as the language is concerned, so if you then cast that int variable to a pointer, the result is indeterminate. (Note also that in C, unlike C++, "const" really means that it is read-only, not that it is a constant expression, so that doesn't change anything.) However, even if the resulting pointer is not a null pointer, dereferencing it is still UB unless it points at a valid C object. So if the compiler can statically prove that for this architecture, there's no valid C object at that address (e.g. because the compiler itself never produces code that would result in objects placed at that address), it can still treat it as UB, same as dereferencing a literal 0.
- shadowgovt 2y agoHow does that interact with using C++ to access hardware features via direct memory, such as UART registers on embedded systems? Is all of that considered UB because the compiler can't prove there's anything at the UART "magic" addresses?
- int_19h 2y agoAs far as ISO C++ is concerned, it is. In practice, of course, a useful C++ compiler would let you do it, somehow. But that is firmly in the realm of implementation-specific stuff (keeping in mind that UB can mean anything including being well-defined by a specific implementation.
- EasyMark 2y ago[deleted]wrong thread