Is a range-based loop over a default constructed std::span undefined behavior?

120 Views Asked by At

I am wondering whether a range based loop over a default constructed std::span is defined behavior since I am conditionally assigning to a default constructed std::span before looping. For example can I do the following?

#include <span>

int main()
{
    std::span<char> s;
    for (auto c : s) {
        // do something
    }

    // should be equivalent to
    for (char* p = nullptr; p < (char*)(nullptr) + 0; ++p) {
        // do something
    }
}

This answer says the following about additive expressions involving pointers:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

So strictly speaking, the operation of adding 0 to (char*)(nullptr) is undefined because the operand (char*)(nullptr) does not point to an element in the same array object.

I am wondering if this case is still defined behavior?

I think it is well-defined because the following code does not compile:

int main() {
    constexpr char* a{nullptr};
    constexpr char* b{a+1};
    return 0;
}

But it does compile if we replace a+1 by a+0. So there must be indeed a special rule which allows adding 0 to a nullptr.

0

There are 0 best solutions below