C++ puzzle #1 (based on C++17)

#include <cstdint>

auto foo(uint8_t n) {
    while(true) {
        ++n;
    }
    return n;
}

int main() {
    return foo(0);
}

With given code, pick one answer:

  • Guaranteed to return 0 from main.
  • Guaranteed to return something other than 0 from main.
  • Undefined behavior.
  • Implementation defined.
  • Will not compile.
Click here for the answer

The correct answer is: Undefined behavior.

In the ยง1.10.27 we read:

The implementation may assume that any thread will eventually do one of the following:
- terminate,
- make a call to a library I/O function,
- access or modify a volatile object, or
- perform a synchronization operation or an atomic operation.

In foo here is an endless loop which would not satisfy any of the above states => the behavior is undefined.

Thanks for reading o/