TIL that if and else have common scope:
if (int x = foo()) {
// ....
}
else if (int x = bar()) {
// ...
}
else {
cout << x; // which x here?
}
I checked ( https://godbolt.org/g/mAvW7B ) that x in else is first.
But why? What is the explanation of this non-obvious behavior?
In this example:
if (int x1 = foo()) {
// ....
}
else if (int x2 = bar()) {
// ...
}
else {
cout << x2; // why x2 is visible here
}
Why x2 is visible in last else then? And why in the first case x is from first if?
Aucun commentaire:
Enregistrer un commentaire