Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to understand return statement in isEmpty function of stack implementation

Tags:

c++

c

stack

I have isEmpty() function in my stack. And it looks something like below.

bool Mystack<T>::isEmpty() const    //function 1
{
     if(top==-1)
          return true;
     else 
          return false;
}

I saw a couple of online code for isEmpty(), which I could not understand. Below is the snippet.

bool Mystack<T>::isEmpty() const    //function 2
{
    return top == -1;
}

Question 1: Are both the functions doing the exactly the same task?

Question 2: If yes, then can some one please explain how the syntax in function 2 performing its task without using any if statement.

like image 540
tanz Avatar asked Dec 19 '25 20:12

tanz


2 Answers

top == -1 is an expression. Assuming no operator overloads are involved, its return type is bool. It will have the value true if top equals -1 and the value false if that's not the case.

return top == -1; means "return the value of the expression top == -1". As I've shown above, this value is either true or false. These coincide exactly with the values returned from the if()-based code, so the two codes are equivalent.

In my code, I tend to use parentheses around "syntactically unusual" return statements, and I consider == one of them. So I would write this in my code (and I would certainly prefer it to the if version):

return (top == -1);
like image 56
Angew is no longer proud of SO Avatar answered Dec 22 '25 12:12

Angew is no longer proud of SO


Yes, both functions work exactly the same. They return whether top equals -1.

In the first code, this is written somewhat "explicitly" (from the reader's perspective). Its English equivalent would be (roughly):

Evaluate the expression top == -1. If the result is true, then return true, else return false.

The second code does it more subtly, and its rough English equivalent would be:

Return the result of the expression top == -1.

like image 20
Masked Man Avatar answered Dec 22 '25 12:12

Masked Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!