mullock
mullock

Reputation: 95

C Programming Return (!int) when int return value expected?

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

Answers (5)

Greg Hilston
Greg Hilston

Reputation: 2424

Its because of what you're returning.

isEmptyArray means

  • a return of "true" says the array is empty
  • a return of "false" says the array is not

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

Gupt Sher
Gupt Sher

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

mazhar islam
mazhar islam

Reputation: 5629

  • In C, zero 0 is treated as boolean false.
  • Any other non zero value is boolean true.
  • By default 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

dlavila
dlavila

Reputation: 1212

the return value is playing the role of a boolean, if count is 0 return 1, otherwise return 0

Upvotes: 3

unwind
unwind

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

Related Questions