Skip to main content

Section 7.9 Boolean functions

Functions can return boolean values, just like any other type, which is often convenient for hiding tests inside functions. If you think you might want to check the parity (evenness or oddness) of numbers often, you might want to โ€œwrapโ€ this code up in a function, as follows:
#include <iostream>
using namespace std;

bool isOdd(int number) {
    bool result = false;
    if (number % 2 == 1) {
        result = true;
    } else {
        result = false;
    }
    return result;
}

int main() {
    cout << isOdd(3) << endl;
    cout << isOdd(4) << endl;
    cout << isOdd(15) << endl;
}
The name of this function is isOdd. It is common to give boolean functions names that sound like yes/no questions. The code itself is straightforward, although it is longer than it needs to be. There are multiple ways to write the code for that function. We could return the answer as soon as it is identified:
bool isOdd(int number) {
    if (number % 2 == 1) {
        return true;
    } else {
        return false;
    }
    // never get here!
}
As soon as the code hits a return, it leaves the function and returns the value. So in that version the function will never reach the line where the comment is. Returning from many places in a function can get confusing, so many programmers prefer to try to stick to one return statement at the very end. Even if we restrict ourselves to that structure, we can simplify things by recognizing there is no need to change the variable to false if the number is not odd:
bool isOdd(int number) {
    // This default value will be used if it is not changed in the if
    bool result = false;
    if (number % 2 == 1) {
        return true;
    }
    return result;
}
Finally, we could recognize that the expression number % 2 == 1 has a boolean value that matches what we want to return. That means we could write the function as just:
bool isOdd(int number) {
    return number % 2 == 1;
}

Checkpoint 7.9.1.

Checkpoint 7.9.2.

Construct a block of code that first checks if a number x is positive, then checks if itโ€™s even, and then prints out a message to classify the number. It prints โ€œbothโ€ if the number is both positive and even, โ€œevenโ€ if the number is only even, โ€œpositiveโ€ if the number is only positive, and finally โ€œneitherโ€ if it is neither postive nor even.
You have attempted of activities on this page.