#include <iostream>
using namespace std;
int main() {
if (true) {
int b = 3;
label_one:
cout << b << endl;
int j = 10;
goto label_one;
}
}
In the code above goto
jumps to label_one, making the variable j
be destroyed and reconstructed in each cycle. But what happens to the b
variable ? Is it destroyed and reconstructed too or it is never destroyed? According to C++ ISO:
Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.
My interpretation is that all variables in if
scope should be destroyed, but if thats the case, when are they re-initialized(variable b
in my code)?
As the quoted text says, a variable is destroyed during the goto
only if it is in scope at the point of the goto
statement, but not in scope at the destination label. b
is in scope at both points, so it is not destroyed. Only j
is destroyed.