New to C Programming- Need help understanding !! operator

• 07-17-2012
shellwoo3
New to C Programming- Need help understanding !! operator
Code:

``` int main(void) {   int i =2, j = 1;   printf("%d",  !!i + !j);   return 0; } Working on exercises from my c book. I know the output is 1... not sure why. I read this would be called a cast type for bool.  Is the !i = 1 and the !j = 1 and since 1 = true for bool, then the value is 1? How does the double negative work?```
• 07-17-2012
ssharish2005
! is logical negation operator in C. In C anything of a natural number is considered to be TRUE. In discrete maths a set of natual number that is "for all elements in set (natural numbers) shall be true"

So for example

int i = 1;

'i' now contains natural numbera; which is term of predicate hold to be TURE. When you negate it you get FALSE

TRUE <==> 1
FALSE <==> 0

i=1 <==> TRUE
!i <==> FALSE (!TRUE)
!!i <==> TRUE ( ! ( ! TRUE ) )

Therefore
!!i <==> TRUE <==> 1
!j <==> FALSE <==> 0

0 + 1 <==> 1

Thus the result is 1.

ssharish

PS: Set of natual numbers 0, 1, 2, .... n
• 07-17-2012
laserlight
Quote:

Originally Posted by ssharish2005
In C anything of a natural number is considered to be TRUE.
PS: Set of natual numbers 0, 1, 2, .... n

Rather, in C, zero is considered a false value and non-zero is considered a true value. It is not about "natural numbers", unless you use the definition of the set of natural numbers that excludes 0, but even then you would have said nothing about negative numbers and non-integers.
• 07-17-2012
ssharish2005
Very ture! I quite missed that. I was thinking set of integers and Natural numbers when i was typing. Explicit description like yours perhaps will make it clear.

ssharish
• 07-17-2012
shellwoo3
I get it now. Thanks for showing the steps. :)