Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Whats the scope of a for loop declaration?

Declaration loop SCOPE
0
Posted

Whats the scope of a for loop declaration?

0

C++ allows identifiers to be declared in for loops. For instance, consider numsides in line A below. In pre-Standard C++ specifications, the scope of such an identifier continued to the end of the block that the for loop was declared in. Therefore, to be able to interrogate numsides on line B was ok under those rules. #include int main() { const int maxsides = 99; for (int numsides = 0; numsides A if (…SomeCondition…) break; // blah blah } if (numsides != maxsides) // B std::cout However, toward the end of the standardization process, related to some other rules (about conditional declarations in general), the committee decided that the scope of the identifier should only be within the for, therefore, line B is an error accto Standard C++. Note that some compilers have a switch to allow old style code to continue to work. For instance, the transition model switch is –old_for_init under Comeau C++. In order for line B to work under Standard C++ , line A needs to be split

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123