https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68003
Bug ID: 68003
Summary: Variable declared in condition in for loop is
destroyed too soon
Product: gcc
Version: 6.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: gcc-bugzilla at contacts dot eelis.net
Target Milestone: ---
Consider:
#include <cassert>
#include <iostream>
struct X
{
bool alive = true;
~X() { alive = false; }
explicit operator bool() const { return true; }
} ;
int main()
{
for(int i = 0; X x = X(); assert(x.alive))
if (++i == 3)
break;
else
std::cout << i << std::endl;
}
When compiled with gcc trunk, the program outputs:
1
a.out: t.cpp:14: int main(): Assertion `x.alive' failed.
When compiled with clang trunk, the program outputs:
1
2