Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ~~x and !!x in C?

I am trying to check if any bit of an int x equals to 1, and the answer is !!x. I googled a bit and didn't find anything about why this is correct.

So say if I have a number x is 1010. What would !x be? What is the different between !x and ~x?

like image 857
Anna Avatar asked Jan 28 '26 02:01

Anna


2 Answers

! is a logical operator which takes the value of the operand of scalar type.

To quote C11, chapter §6.5.3.3, Unary arithmetic operators

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. [...]

OTOH, ~ is a bitwise operator which performs bitwise negation of the operand of integer type.

Related,

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. [...]

For example, consider binary number 10.

  • !10 is 0.
  • ~10 is 01.

EDIT:

FWIW, is you use !!, the result you can get is either 0 or 1. OTOH, is you use ~~, you get back the original value of the operand.

like image 161
Sourav Ghosh Avatar answered Jan 30 '26 14:01

Sourav Ghosh


The range of possible values of !x are 0 and 1.

~ (the bitwise complement) has the same range as its domain.

So ~~x will recover x, but !!x will not necessarily do that.

like image 20
P45 Imminent Avatar answered Jan 30 '26 15:01

P45 Imminent