Okay, I just came back from a quick shower, and the idea came to me just as I started showering
Basically, I was trying to find a way to loop 0 or 1 times, without having to use a control variable other than x and y. For example, this works:
Unfortunately, as soon as it hits the while (x < y) loop, it will print again, erroneously. So I tried to think of some swapping method that could avert this. However, there appears to be a simpler solution: do not reuse x and y. We could write something like:Code:while (x > y) { cout << "x is bigger than y"; x = 0; y = 1; }
Since x and y within each function is local to that functions, the assignment that ends the loop does not affect the x and y from the caller (e.g., the main() function). As such, only one of the functions when called actually prints something, and only once. This is equivalent to the if - else if - else structure that we would normally use.Code:void printGreaterThan(int x, int y) { while (x > y) { cout << "x is bigger than y"; x = 0; y = 1; } } void printEqualTo(int x, int y) { // ... } void printLessThan(int x, int y) { // ... } // ... printGreaterThan(x, y); printEqualTo(x, y); printLessThan(x, y);



LinkBack URL
About LinkBacks



