The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
See also: Boolean values, Boolean Variables | ||
![]() ![]() ![]() ![]() ![]() ![]() |
||
Bool Functions
{ if (x >= 0 && x < 10) { return true; } else { return false; } } The name of this function is isSingleDigit. It is common to give boolean functions names that sound like yes/no questions. The return type is bool, which means that every return statement has to provide a bool expression. The code itself is straightforward, although it is a bit longer than it needs to be. Remember that the expression x >= 0 && x < 10 has type bool, so there is nothing wrong with returning it directly, and avoiding the if statement altogether: bool isSingleDigit (int x){ return (x >= 0 && x < 10); } In main you can call this function in the usual ways: cout << isSingleDigit (2) << endl;bool bigFlag = !isSingleDigit (17); The first line outputs the value true because 2 is a single-digit number. Unfortunately, when C++ outputs bools, it does not display the words true and false, but rather the integers 1 and 0. (There is a way to fix that using the boolalpha flag, but it is too hideous to mention.) The second line assigns the value true to bigFlag only if 17 is not a single-digit number. The most common use of bool functions is inside conditional statements if (isSingleDigit (x)) {cout << "x is little" << endl; } else { cout << "x is big" << endl; }
|
||
Home ![]() ![]() |