Logical NOT in Arduino


Logical NOT is performed using the ! operator. The truth table is given below −

ExpressionOutput
TF
FT

As you can see, the logical NOT inverts the truth value of the expression.

Example

The usage can be understood from the example given below −

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   int i = 10;

   if (!(i > 10)) {
      Serial.println("i is NOT greater than 10");
   }
   else {
      Serial.println("i is greater than 10");
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

The NOT function is often used while waiting for something to become true.

while(!condition){
   //do something
}

For example, if you are waiting for Serial input,

while(!Serial.available()){
   //Wait
}

The above loop will break when Serial.available() returns something greater than 0, i.e., when the serial input is received.

Updated on: 31-May-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements