user2601570 user2601570 - 1 month ago 6
Linux Question

c++ cross initialization jump to case label when initializing a float array

I have 3 classes M , L , P , each have its own .header and .cpp for encapsulation practice i have put relevant functions and attributes respectively in each .header and .cpp

i have this function

float L::calculate(arg,arg,arg,arg)
here that is in L.cpp , its just a fixed formula which arguments taken from the class itselfs . But i have a another class P

In P.cpp , i have get/set of the calculate function of L class . In class P i also have contructors , 1 default and 1 that takes in args (i initialize L in both constructors as well)

then in my class M where all the implementaion comes together .

i am trying to create a float array like this :

float calculateThis[size]; // the size is fixed at 50.


then in a for loop where x is less than size

i did this :

calculateThis[x] = newL[x].caculate(args,args,args,args);
newP.setCalculate(calculateThis[x]);
++x;


I have also declare on top

L newL[size]; //Used for some other methods that i have wrote to get inputs and save it .
P newP[size];


when i compile i get this error :

crosses initialization of ‘float calculateThis[size]’
float calculateThis[size];


Basically i am trying to save the calcuated function that returns a float into a float array

EDIT:

switch(choice)
{
case 1: // 1st Choice.
while(entry<size)
{
//getting user input and saving it by newL.set / newP.set
};
break;

case 2:
float calculateThis[size]; // the size is fixed at 50.
for(x=0,x<size)
{ calculateThis[x] = newL[x].caculate(newL.get(),newL.get(),newL.get(),newL.get());
newP.setCalculate(calculateThis[x]);
++x;
}
break;

default:break;
}

Answer

Use brackets to indicate that this is local scope for calculateThis:

    case 2:
    {
      float calculateThis[size]; // the size is fixed at 50.
      for(x=0,x<size)
      {       
        calculateThis[x] = newL[x].caculate(newL.get(),newL.get(),newL.get(),newL.get());
          newP.setCalculate(calculateThis[x]);
           ++x;
      }
     }break;
Comments