The exclamation point is the C's boolean negation character.
It means give me the boolean opposite of the value. A boolean is either true
or false
, which are 1
or 0
in the C Language.
In C, if
statements execute their conditional statements if the argument is true.
if (a)
means if a
is true (i.e. non-zero)
if (!a)
means if a
is false (i.e. 0)
Therefore:
if (a)
is the same as if (a != 0)
if (!a)
is the same as if (a == 0)
Sometimes you'll see code that uses two exclamation points in a row "!!
"
For example:
int a = !!b;
That ensures a
will be ONLY 0
or 1
, regardless of what the value of b
is.
If b
is ANY non-zero value, the !
operator will treat it as though it is true true
, which it treats as being the same as 1
So:
!0 == 1
!1 == 0
!52 == 0
!25692 == 0
The second !
does the boolean inversion again, so:
!!0 == 0
!!1 == 1
!!52 == 1
!!25692 == 1