A simple question on return statement

Hi all:

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?

Thanks.
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.
Last edited on
closed account (Dy7SLyTq)
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):
1
2
3
if(top == 0) return true; return false;
return top == 0 ? true : false;
if(top) return false; return true;
Thanks for the reply. I got it.

To DTSCode, you are right, actually I did test your suggestions and it worked. I understand what this "return" essentially means.
closed account (Dy7SLyTq)
no problem. while not neccesary to understand this, an interesting topic to read up on that goes along with this is type conversion
Topic archived. No new replies allowed.