TITLE: Scope of variables declared in for() while() if() PROBLEM: [ There was a lot of discussion concerning changes recently adopted by the C++ working committee concerning the scope of variables declared in "for/while" loop headers and in "if" statements. In particular, discussion centered on code like that below (which is currently legal). void bar() { for (int i = 0; i < 5; i++) { ; } if (i == 5) { ... } } -adc ] RESPONSE: Brian Hook I was under the impression that scoping of variables in 'for' statements has already been APPROVED. As has declaration of variables within if statements, i.e. the following is now legal: if ( FILE *fp = fopen( "file.name", "r" ) ) { } RESPONSE: es@crl.com (Eric Smith), 20 Jul 94 What is the scope of fp? To be consistent it seems like it should go out of scope at the end of the if statement, or at the end of the associated else statement, if any. (To be consistent with the new for scope.) RESPONSE: kanze@us-es.sel.de (James Kanze) Correct. The scope of the variable declared in the `if' statement is the `if' statement itself (including an eventual `else' part). I don't know if any compilers already implement this. (Maybe Borland. It was part of the RTTI proposal, and they implement that.) RESPONSE: kanze@us-es.sel.de (James Kanze) Actually, the proposal was adapted at San Diego, four months ago. The proposal had originally been suggested several years ago, and voted down, so I think people who supposed that there would be no change in the scope of the variable can be excused. The proposal was reconsidered, and adapted, as a result of the allowing declarations in conditional expressions (while, if, etc.), and the desire that the scope of the variable in the for be consistent with the scope of these variables. I am curious as to how compilers will handle the transition phase. I would also point out that the change may cause a silent change in the meaning of a program. Consider the following: int i = 1 ; int main() { for ( int i = 0 ; i < 2 ; i ++ ) ; cout << i << endl ; return 0 ; } Under the rules in the ARM, this program will print "2". Under the new rules, it will print "1". Under both rules, it is fully conforming.