Lokesh Chebrolu
Lokesh Chebrolu

Reputation: 33

C programming ! Arithmetic operator operation

#include <stdio.h> 
int main()
{ 
    int a = 10, b = 5, c = 3; 
    b != !a; 
    c = !!a; 
    printf("%d\t%d", b, c); 
}

This is the c code. I got the output as 5 1 . I cant get the operation behind this expressions of b and c. Can anyone please explain how?

Upvotes: 1

Views: 180

Answers (2)

selbie
selbie

Reputation: 104524

Since a is initially 10, then !a evaluates to 0

Therefore b != !a evaluates to 5 != 0, which evaluates to a true expression (1). (But as Michael points out in his answer, this is not an assignment operator).

c = !!a which evaluates to c = !0, which evaluates to c = 1

Explanation: The language lawyers may scold me on this, but ! operator applied to a non-zero expression evaluates to zero. The ! operator applied to any false (0) expression evaluates to 1.

Upvotes: 6

Jabberwocky
Jabberwocky

Reputation: 50775

It's a trick question.

b != !a; is basically a NOP. It just evaluates to 1 but doesn't change the content of b. You can remove this line altogether and you'll get the same output.

Upvotes: 2

Related Questions