compile error. help...

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
New poster
Posts: 4
Joined: Mon Mar 06, 2006 7:11 am
Location: China

compile error. help...

Post by winterflower » Mon Mar 06, 2006 7:25 am

using namespace std;
void main(){
int n;
int k;
double *p;
while(n-- > 0){
p = new double[k];
double sum = 0;
for(int i=0;i<k;i++){
sum += p;
int c = 0;
double ave = sum/(double)k;
if(p > ave) c++;
delete p;
double x = (double)100*c/k;

A simple problem but I've got a lot of CE.
Why ?Thanks in advance!!
Hello world!

A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 » Mon Mar 06, 2006 8:49 am

This part of your code:

Code: Select all

if(p[i] > ave) c++; 
i is undeclared.

New poster
Posts: 4
Joined: Mon Mar 06, 2006 7:11 am
Location: China

Post by winterflower » Mon Mar 06, 2006 9:14 am

Thanks a lot!
I got AC now by adding the declaration of the ''int i''.
But I still don't know why this correct code got such result in VC++.
The former code I posted works well in it. :o
--------------------Configuration: aver - Win32 Debug--------------------
C:\Mycpp\aver.cpp(21) : error C2374: 'i' : redefinition; multiple initialization
C:\Mycpp\aver.cpp(15) : see declaration of 'i'
Error executing cl.exe.

aver.exe - 1 error(s), 0 warning(s)
Hello world!

A great helper
Posts: 286
Joined: Tue Mar 25, 2003 8:36 am
Location: calcutta

Post by sumankar » Mon Mar 06, 2006 9:34 am

ANSI C++ Committee defined that the scope of such variable is the scope of
'for' itself. Before this new standard the scope was not defined and developers
of compilers could do what they want.

g++ and VC++(ver x) has different scoping for variables. For g++ the scope is till the closing brace of the loop whereas for VC++ it is till the end of the function (which is *not* the
correct one, as far as the standard goes.)

AFAIK, g++ 2.7.x implemented this change as the default one. Use -fno-for-scope with g++
to get a VC++ like effect.

User avatar
Krzysztof Duleba
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland

Post by Krzysztof Duleba » Mon Mar 06, 2006 4:31 pm

I'm pretty sure this is a problem with old versions of VC++ only. Those from Visual Studio 2003 and 2005 should conform to the standard.
For millions of years, mankind lived just like the animals. Then something happened which unleashed the power of our imagination. We learned to talk and we learned to listen...

Post Reply

Return to “C++”