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.
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);
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 istrue, then returntrue, else returnfalse.
The second code does it more subtly, and its rough English equivalent would be:
Return the result of the expression
top == -1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With