C Programming Return (! Int) when expected int return value?
int isEmptyArray (struct arrayBagStack * b) {
return(!b->count);
}
I have this piece of code that appears as the correct answer. I don't understand the concept showing the return of a (!) Not Int value when an Int value is expected. Can someone please explain why this will work and what is the expected behavior?
count
is a member variable from struct arrayBagStack
.
source to share
There are no type changes here.
The not ( !
) operator simply evaluates another integer value, which is then returned.
In this case, it is used to convert count to true / false to answer the question if the array is empty. If b->count
equal to 0, !0
- 1
, which means "true". If any other value, !
converts this value to 0
, that is, "false".
In my opinion, such code may not be optimal; it should be simple:
return b->count != 0;
Which generates accurate values ββfor all values count
, but is clearer.
source to share
- In C, null is
0
treated as a booleanfalse
. - Any other nonzero value is boolean
true
. - By default
true
means1
.
So when you return(!b->count)
, which is equivalent b->count ! = 0
, return either true
or false
. But since it is a type return
int
, then if it b->count
is 0
, then it isEmptyArray
will return 1
, 0
otherwise.
source to share
Because you are coming back.
isEmptyArray means
- Returning "true" says the array is empty.
- returning "false" tells the array not
So if b -> count is NULL, then you want to return true for empty, so you invert it
and if b -> count is not NULL, you want to return false for non-empty, so you invert it
If you want to remove !, rename the function to isNotEmptyArray to follow the logic
source to share