PRB: Variable Scope in for-statement Extends Beyond Loop

Article translations Article translations
Article ID: 167748 - View products that this article applies to.
This article was previously published under Q167748
Expand all | Collapse all

SYMPTOMS

If you declare the same variable in two different for-statements, the following error may appear:
Test.cpp(4) : error C2374: 'i' : redefinition; multiple initialization

CAUSE

The scope of a variable declared in the initialization part of a "for" loop is given local scope, as if it had been declared immediately prior to the for-statement.

RESOLUTION

Compile with /Za, Disable Language Extensions. To select this option in Developer Studio, select Project, Settings, and then click the C/C++ Tab. Change the Category to Customize and select Disable Language Extensions.

If you cannot use the /Za option, you can work around the problem by #defining the "for" keyword as follows:
#define for if(0);else for
				

MORE INFORMATION

/* Compile Options Needed to compile without error: /Za */ 

 /* test.cpp */ 
 void main()  {
for (int i=0; i<10; i++)
   ;
for (int i=0; i<15; i++)
   ;
 }
				

Properties

Article ID: 167748 - Last Review: July 5, 2005 - Revision: 1.1
APPLIES TO
  • Microsoft Visual C++ 5.0 Standard Edition
  • Microsoft Visual C++ 6.0 Service Pack 5
Keywords: 
kblangcpp kbprb KB167748
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com