Reputation: 21
I know that output of the program is "GOD"
.
How is the code written in the if
statement true?
This is Boolean calculation and I don't understand this.
Please someone elaborate what is happening.
void main() {
int a=10;
if(!(!a)==!0)
printf("GOD");
else
printf("Good");
}
Upvotes: 0
Views: 89
Reputation: 311088
In the expression of the if statement
if(!(!a)==!0)
there is used the negation operator !
.
According to the C17 Standard (6.5.3.3 Unary arithmetic operators):
5 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. The expression !E is equivalent to (0==E).
So, for example, the sub-expression !0
evaluates to "1 if the value of its operand compares equal to 0". So the right operand of the equality operator is equal to the integer value 1
.
On the other hand, the left operand of the equality operator that represents the expression !(!a)
that may be rewritten like !!a
contains two negation operators. As initially a
is not equal to 0
then applying the first negation operator (negation operators are evaluated from right to left) yields the integer value 0
. And after that applying the second negation operator to the value 0
yields the integer value 1
.
As a result you actually have
if( 1 == 1 )
that in turn yields the integer value 1
that is the above if statement is equivalent to
if ( 1 )
So the sub-statement of the if statement gets the control.
Of course instead of using this compound expression in the if statement
if(!(!a)==!0)
you could just simply write
if( a )
because according to the any C Standard (the C17 Standard, 6.8.4.1 The if statement):
2 In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed.
Upvotes: 0
Reputation: 386541
!
evaluates to 1
if the operand's value is zero, and 0
otherwise.
==
evaluates to 1
if both operands have the same value, and and 0
otherwise.
!(!a)==!0
// ⇓ Replace variables with their values.
!(!10)==!0
// ⇓ `10` is non-zero, so `!10` is `0`.
!(0)==!0
// ⇓ Remove useless parens.
!0==!0
// ⇓ `0` is zero, so `!0` is `1`.
1==1
// ⇓ The two values are equal, so `1==1` is `1`.
1
1
is non-zero, so the "then" statement is executed.
Upvotes: 2