#include /*************************************************** * Safe increment * * Write a function that increments a variable, but * only if doing so will not cause its value to * exceed a given upper bound. * * For example, if * * m == 42 * * and the upper bound is 50, repeatedly calling * * increment( m, 50 ); * * should increase m until it reaches 50. * * Once m reaches 50, subsequent calls should leave * its value unchanged. * * The first parameter must be passed by reference * because the function is intended to modify the * variable supplied by the calling function. * * The bound is passed by value and declared const * because the function has no reason to change it. ***************************************************/ // Function declarations int main(); void increment( int &a, int const bound ); // Function definitions int main() { int m{ 42 }; for ( int k{ 0 }; k < 16; ++k ) { increment( m, 50 ); std::cout << m << std::endl; } return 0; } /*************************************************** * increment * * Increment a only if its new value will not exceed * bound. ***************************************************/ void increment( int &a, int const bound ) { return; } // Hint: // // If a is less than bound, it is safe to increment // a. // // If a is already equal to or greater than bound, // leave it unchanged. // // Be careful about testing // // a + 1 <= bound. // // Why might calculating a + 1 itself be a problem? // Solution: /* void increment( int &a, int const bound ) { if ( a < bound ) { ++a; } } */ /*************************************************** * Why not use != ? * * You might be tempted to write * * if ( a != bound ) { * ++a; * } * * This works if a begins below the bound and reaches * it by repeated increments. * * However, suppose * * a == 60 * bound == 50. * * Because 60 != 50, the function would increment a * to 61, which is exactly the opposite of what we * want. * * The appropriate condition is therefore * * a < bound. * * * Why not test a + 1? * * We could apparently write * * if ( a + 1 <= bound ) { * ++a; * } * * but this has an unnecessary problem. If a already * contains the largest possible int, calculating * * a + 1 * * causes signed integer overflow. * * Testing * * a < bound * * avoids the addition entirely and expresses the * required condition more directly. ***************************************************/