I don't understand if I have created an infinite loop or it is just taking long.
int wuerfeln_bis_wurfverteilung(Wurfverwaltung ww) { //takes object of class with x number of die rolls
Wurfverwaltung xx(ww.anzahl); //creates object with x (from param.) no. of rolls
cout << xx << endl;
int z=0;
while (!(xx == ww)){ // while the two objects are unequal
Wurfverwaltung xx(ww.anzahl); //keep creating new objects
z ; //and increase z by one
cout <<xx<< " " << z<< " ";
}
return z;
}
//class looks like this
class Wurfverwaltung{
friend int wuerfeln_bis_wurfverteilung(Wurfverwaltung&);
private:
unsigned int anzahl;
Wurf *w; // pointer to an array of objects from a previous class
... bunch of functions
Question: is it always testing for xx from the before the while loop and comparing to ww? or is xx getting updated every loop? the code doesn't seem to break even if I take 2 as the no. of rolls. (answered. Thanks!) Edit: The point of the function is to take an object with a random array and recreate an array with the same combination and return the number of attempts it took.
CodePudding user response:
You are shadowing a variable by creating a new variable with the same name in a new scope.
int wuerfeln_bis_wurfverteilung(Wurfverwaltung ww) {
Wurfverwaltung xx(ww.anzahl); // 1
cout << xx << endl;
int z=0;
while (!(xx == ww)){
Wurfverwaltung xx(ww.anzahl); // Creates new variable, doesn't change (1)
z ;
cout <<xx<< " " << z<< " ";
}
return z;
}
If you change it to x = ww.anzahl;
you'll be changing the values and maybe exit the loop.
(Also note that !(xx == ww)
is equivalent to xx != ww
and might be clearer.)
You compiler can help you detect these kind of issues, but you have to activate more flags (-Wshadow
in this case on GCC)
CodePudding user response:
The condition of the while loop
while (!(xx == ww)){ // while the two objects are unequal
Wurfverwaltung xx(ww.anzahl); //keep creating new objects
z ; //and increase z by one
cout <<xx<< " " << z<< " ";
}
deals with the variable xx declared before the loop
Wurfverwaltung xx(ww.anzahl);
The variable xx declared within the loop does not influence on the condition of the loop. It just hides the variable declared before the while loop in the compound statement of the while loop. That is the declaration region of the variable declared in the while loop is the compound statement. Outside the compound statement the variable does not exists.
So the initial value of the condition of the while loop
while (!(xx == ww)){
is not being changed and you have an infinite loop.