Boolean Valued Function

One nice advantage to the boolean type is to create functions that return true or false. These can be use to test if a complicated condition is true. The details of the complicated test will be hidden inside the function, and the function call will add clarity to the program.

For example, to test if a character is a letter, a function like this could be written:

bool function is_letter (char letter) {
	bool result;
	if (letter >= 'A' && letter <= 'Z' ||
	    letter >= 'a' && letter <= 'z') 
		result = true;
	else
		result = false;
	return result;
}

This could also be simplied as

bool function is_letter (char letter) {
	if (letter >= 'A' && letter <= 'Z' ||
	    letter >= 'a' && letter <= 'z') 
		return true;
	else
		return false;
}

And sometimes, the function can even be simplified as

bool function is_letter (char letter) {
	bool result;
	result = (letter >= 'A' && letter <= 'Z' ||
	    	  letter >= 'a' && letter <= 'z');
	return result;
}

Of course, the slickest siumplification is

bool function is_letter (char letter) {
	 return(letter >= 'A' && letter <= 'Z' ||
	        letter >= 'a' && letter <= 'z') ;
}

This function could then be used as follows in a main program

	char answer;
	
	cout << "Enter a letter: "
	cin >> answer;

	if (! is_letter(answer) )
		cout << answer << " is not a letter\n";

This is much clearer than putting the details of the boolean test in the main program.