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

.

+3


source to share


5 answers


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.

+9


source


the return value plays the role of a boolean value if count

there is a 0

return 1

, otherwise it returns0



+3


source


  • In C, null is 0

    treated as a boolean false

    .
  • Any other nonzero value is boolean true

    .
  • By default true

    means 1

    .

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.

+3


source


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

+2


source


Not that he changed the data type from int

to !int

.

!

will work with the value b->count

. So if it is 0 !b->count

will result in 1

otherwise 0

.

+2


source







All Articles