Reputation: 95
int isEmptyArray (struct arrayBagStack * b) {
return(!b->count);
}
I have this code snippet that is shown as a correct answer. I do not understand the concept that is shown of returning a (!) Not Int value when the Int value is expected. Can someone explain why this would work and what is the expected behavior?
count
is a int member variable of struct arrayBagStack
.
Upvotes: 3
Views: 265
Reputation: 2424
Its because of what you're returning.
isEmptyArray means
So if b -> count is NULL, then you'd want to return true for empty, so you inverse it
and if b -> count is not NULL you want to return false for not empty, so you inverse it
If you wanted to remove the !, then rename the function to isNotEmptyArray to follow the logic
Upvotes: 2
Reputation: 21
Its not that it will change the datatype from int
to !int
.
!
will work on the value of b->count
. So if it is 0, !b->count
will result in 1
, otherwise 0
.
Upvotes: 2
Reputation: 5629
0
is treated as boolean false
.true
. true
means 1
.So when you return(!b->count)
which is equivalent to b->count ! = 0
return either true
or false
. But as the return
type is int
then if b->count
is equal to 0
then isEmptyArray
will return 1
, 0
otherwise.
Upvotes: 3
Reputation: 1212
the return value is playing the role of a boolean, if count
is 0
return 1
, otherwise return 0
Upvotes: 3
Reputation: 400159
There is no change of type happening here.
The not operator (!
) simply computes another integer value, which is then returned.
In this case, it's being used to convert the count into a true/false value to answer the question whether the array is empty. If b->count
is 0, !0
is 1
, which means "true". If it's any other value, !
will convert that to 0
, i.e. "false".
In my opinion code like this fails to be optimally clear; it should just be:
return b->count != 0;
Which generates the exact same values for all values of count
, but is way clearer.
Upvotes: 9