lundi 31 mai 2021

C++ "else" statement when the preceding line has multiple "if" statements

The following C++ program

#include <iostream>

int main() {
    for(int i=0; i<5; i++) for(int j=0; j<5; j++){
        if(i==1) if(j==2) std::cout << "A " << i << ' ' << j << std::endl;
        else std::cout << "B " << i << ' ' << j << std::endl;
    }
    return 0;
}

outputs

B 1 0
B 1 1
A 1 2
B 1 3
B 1 4

From this I infer that the "else" statement is referring to the second "if".

Is this behavior described in the C++ standard? Is there a reason for implementing it this way? I intuitively expected "else" to refer to the first "if".

Aucun commentaire:

Enregistrer un commentaire