> I just got the MSVC++ program and was > trying out your sample programs on your web page. However, when I tried the > prime number program it gave me this error: > > C:\My Documents\My Programs\p1.cpp(15) : error C2374: 'i' : redefinition; > multiple initialization > C:\My Documents\My Programs\p1.cpp(12) : see declaration of 'i' > > How would this error be fixed so that the program works under MSVC++? > Thanks for pointing this out. The "error" occurs because the installation of MSVC++ that you were using (which may be the same as in the Lab) has not yet been updated to conform to the new C++ standard. Here is the code you've referred to: > for (int i = 2; i <= s/2; ++i) // Sieve of Eratosthenes (up to s) > if ( primes[i] ) > for (int j = 2*i; j <= s; j+=i) > primes[j] = 0; > > for (int i = 2; i <= s && i < N; ++i) // Check primality of N. > if ( primes[i] ) > if ( !(N%i) ) > { > factor = i; > break; > } Note that I have defined i twice in this fragment; once for each for-loop. In the original definition of C++, the scope of a variable declared inside the header of a "for" loop (like i) extended to the end of the block *in which the "for" loop occurred.* Your installation is using this original, outdated rule. Under that rule, the above fragment makes the error of defining i twice in the same scope. In the most recent definition of C++, the scope of a variable declared inside the header of a "for" loop extends only to the end of the "for" loop body. This is the definition assumed by my example, and it's the definition used by the compiler I tested my code on. The code can easily be changed so that it works with both standards: > int i; > for (i = 2; i <= s/2; ++i) // Sieve of Eratosthenes (up to s) > if ( primes[i] ) > for (int j = 2*i; j <= s; j+=i) > primes[j] = 0; > > for (i = 2; i <= s && i < N; ++i) // Check primality of N. > if ( primes[i] ) > if ( !(N%i) ) > { > factor = i; > break; > } File p2.cpp, posted 10/21/99, incorporates this modification and compiles and runs under the default installation of MSVC++. I will try to find out how we can configure the compilers in the lab to better support the new C++ standard. In the meantime, it may be best to declare (index) variables outside of loop headers.