Search code examples
c++floating-pointstdarray

Is it undefined behavior to iterate over an std::array initialized in the for-loop?


// This snippet
for (const float t : std::array{ 0.0f, 0.33f, 0.66f, 1.0f }) {
  std::cout << "t = " << t << "\n";
}
// Yields the following (incorrect) values:
t = -3.91649e-28
t = 4.59037e-41
t = 2.66247e-44
t = 0

// Whereas this snippet ...
auto vals = std::array{ 0.0f, 0.33f, 0.66f, 1.0f };
for (const float t : vals) {
  std::cout << "t = " << t << "\n";
}
// Yields the following (correct) values:
t = 0
t = 0.33
t = 0.66
t = 1

Is the first snippet undefined behavior, or is this a compiler bug?

Update: This was compiled with Visual Studio 16.7.2 and 16.7.3 using std=c++17 and /Ox. The error persists in my bug project, but I have not been able to reproduce it in a small project using similar build flags. The problem persist if I use integers instead of floating points.


Solution

  • No, it is not UB since range-for loop does extend lifetime of temporary range. https://en.cppreference.com/w/cpp/language/range-for

    If range_expression returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the forwarding reference __range, but beware that the lifetime of any temporary within range_expression is not extended.

    Taking into consideration fact, that gcc has no problem with this code it is probably MSVC bug.