I'm testing a simple C++ code from C++ Primer Plus, 6 edition, chapter 10.
The code runs as the book suggested, but I have one simple question.
In a source file, we defined an integer "top" for the index of a stack. The program defines a function called "isempty()" to test if the stack is empty or not. The function is defined as follows:
1 2 3 4
bool isempty()
{
return top == 0;
}
I'm just wondering what exactly does this isempty() return? It should return TRUE or FALSE, I understand. Does it mean if top == 0, then return TRUE, otherwise return FALSE?
isempty() returns a bool.
(top == 0) is a boolean expression. In other words, it gets cast to a boolean expression. isempty() returns the truth value of (top == 0).
In your case, if top == 0, isempty() returns true.
well its testing equality. regardless of where you use it, it has the same effect, for example: int i = some_int == some_other_int;
it breaks down to either true(1) or false(0). so an if only executes if the whole condition resolves to true. the return statement executes no matter what. it returns true(1) if top is at zero, and false(0) for any other value. some other ways you could have written that (kept to one line each cause im lazy):