Can't understand the return statement in the isEmpty function of the stack implementation
I have an isEmpty () function on my stack. And it looks something like this.
bool Mystack<T>::isEmpty() const //function 1
{
if(top==-1)
return true;
else
return false;
}
I saw a couple of online code for isEmpty () that I couldn't figure out. Below is a snippet.
bool Mystack<T>::isEmpty() const //function 2
{
return top == -1;
}
Question 1: Do both functions perform exactly the same task?
Question 2: If so, can someone explain how the syntax in function 2 accomplishes its task without using an if statement .
source to share
top == -1
- this expression. Assuming no operator overloads are involved, its return type bool
. It will matter true
if top
equal -1
and value false
if not.
return top == -1;
means "return the value of the expression top == -1
". As I showed above, this value is equal to true
or false
. They are exactly the same as the values ββreturned from the code if()
, so both codes are equivalent.
In my code, I usually use parentheses around "syntactically unusual" return statements, and I am considering ==
one of them. So I would write this in my code (and I would prefer it in version if
):
return (top == -1);
source to share
Yes, both functions work exactly the same. They return if top
equal -1
.
In the first code it is written somewhat "explicitly" (from the point of view of the reader). Its English equivalent would be (roughly):
Evaluate the expression
top == -1
. If resulttrue
, returntrue
, else returnfalse
.
The second code does it more subtly, and its rough English equivalent would be:
Return the result of an expression
top == -1
.
source to share
Yes, they do the same.
Think about the semantics of the operator if
. The condition is evaluated as bool
and tested for true
. top==-1
will either evaluate as true
or false
, if it evaluates as true
, then the first form is executed and returned true
, otherwise the second form is evaluated and returned false
. This is exactly the same as the second version, just more detailed.
source to share
Answer 1: Yes, the same task.
Answer 2: I have no exact idea c++
, but logically
return top == -1;
can be broken down into
-
check if the value is equal
top
1
or not.1.1 if equal, return
1
[orTRUE
] (as a result of success of the comparison)1.2 if not, return
0
[orFALSE
] (as a result of comparison failure)
As a reference, from the standard document C99
, chapter 6.8.6.4, clause 3,
If a return statement is executed with an expression, the value of the expression is returned to the caller as the value of the function call expression.
and for c++11
, chapter 6.6.3, paragraph 2,
., The return statement with a non-void expression can only be used in functions that return a value; the value of the expression is returned to the calling function ....
source to share