Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is !x equal to true when x is negative?

Tags:

c

int main() {
    
    int x = -1;
                    
    if (!x) {
        printf("Yes\n");
                
    }
}

Is !x true when x is a negative number or it's true when it's only 0?

like image 306
user157629 Avatar asked Dec 17 '22 12:12

user157629


2 Answers

For any non-zero x, !x will be zero. So, for x == -1, !x is false.

From cppreference:

The logical NOT operator has type int. Its value is ​0​ if expression evaluates to a value that compares unequal to zero. Its value is 1 if expression evaluates to a value that compares equal to zero.

like image 85
Adrian Mole Avatar answered Dec 30 '22 02:12

Adrian Mole


Any non-zero value is true even if it is negative value(e.g. -1 is true). So, negation of true is false. In the case of x=-1, if (x) will be evaluated to true. Thus, if(!x) will be false, and the printf("Yes\n"); will never be executed.

like image 36
imtithal Avatar answered Dec 30 '22 00:12

imtithal