
376 views
Logical NOT (!) Operator in C
The logical NOT operator (!) is a unary operator that is used to negate the value of a boolean expression. It is also called the “logical negation” operator. The ! operator operates on a single boolean operand, and it returns the opposite of the operand’s boolean value.
Here’s the basic syntax of the logical NOT operator:
result = !expression;
expression: A boolean expression that can be either true (non-zero) or false (zero).result: The result of applying the logical NOT operator to the expression. It will be1(true) if the expression is false, and0(false) if the expression is true.
Here are some examples of how the logical NOT operator is used:
C
#include <stdio.h>
int main() {
int x = 5;
int y = 0;
// Using the logical NOT operator to negate boolean values
int result1 = !x; // result1 is 0 (false) because x is non-zero (true)
int result2 = !y; // result2 is 1 (true) because y is zero (false)
// Using the logical NOT operator in conditional statements
if (!x) {
printf("x is false (zero).\n");
} else {
printf("x is true (non-zero).\n");
}
if (!y) {
printf("y is false (zero).\n");
} else {
printf("y is true (non-zero).\n");
}
return 0;
}In this example:
result1is assigned the value0because!xnegates the non-zero value ofx, making it0.result2is assigned the value1because!ynegates the zero value ofy, making it1.- The logical NOT operator is used in conditional statements to check the truthiness of variables. If the expression inside
ifevaluates totrue(non-zero), then the code block inside theifis executed; otherwise, the code block inside theelseis executed.
So, the logical NOT operator is useful for inverting the boolean value of an expression or variable, effectively converting true to false and vice versa.