jeudi 29 mars 2018

Why if ... else if ... else have common scope? And what scope is common with last else?

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