Home > database >  Is there a way to 'reset' a functions variables?
Is there a way to 'reset' a functions variables?

Time:05-17

I recently made a function to compare an array of numbers to a single value which returns the closest value to the single value out of the array. This works perfectly well when you only use it only once but if I use it again in another instance of the code, It returns an unexpected value (usually the previous single value used before). Here is the function that I am using:

double closestval (double num1, int amountofnums, double *comps){

double storagecomps[amountofnums];


for (int i = 0; i < amountofnums; i  ){


storagecomps[i] = {comps[i]};
/* Storing the array of numbers for later as I will be changing them */
}



double smallval = 0.0001; /* tiny value used to increment/decrement
values in the array to the comparison variable.*/

int_fast64_t compi [amountofnums]; /* this variable keeps track of how many times it needs to decrement/increment the values in the array to approach the variable*/

for (int i = 0; i < amountofnums; i  ){

compi[i] = 0;
}


for (int i = 0; i <= amountofnums; i  ){

while (comps[i] > num1){

comps[i] -= smallval;
compi[i]  ;

}
while (comps[i] < num1){


comps[i]  = smallval;
compi[i]  ;

}

double recholder[3] = {10000000, 0,};

// This area finds the 
for (int i = 0; i < amountofnums; i  ){

if (compi[i] < recholder[0]){
recholder[0] = compi[i];
recholder [1] = i;
recholder[2] = storagecomps[i]; /* if the amount of iterations to approach the single variable is less than the previous record holder, it becomes the new one.
*/
}

}

return recholder[2];


}

I am relatively sure this is because (in one way or another) the variables in the function are not being redefined properly or at all. Much thanks if you can show me where I've gone wrong!

CodePudding user response:

The problem isn't resetting the variables. The problem is that you are modifying the arguments passed to the function.

To prevent modifications you should use the const keyword:

double closestval (double num1, int amountofnums, const double *comps){

and then fix the errors the compilers throws at you.

If you do want to modify the comps inside the functions but not have it affect the values outside the functions then you should usestd::vector so you can pass them by value and the compiler will copy them:

double closestval (double num1, int amountofnums, std::vector<double> comps){

You should really do that anyway as you should forget all about C-style arrays till you are an expert.

  • Related