A simple question on return statement

Dec 26, 2013 at 4:41am
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.
Dec 26, 2013 at 5:10am
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 Dec 26, 2013 at 5:11am
Dec 26, 2013 at 5:15am
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;
Dec 26, 2013 at 5:30am
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.
Dec 26, 2013 at 5:39am
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.