OneBite.Dev - Coding blog in a bite size

Check If Two Variable Not Equal In C++

Code snippet for how to Check If Two Variable Not Equal In C++ with sample and detail explanation

C++ programming offers a variety of ways to compare variables. In this article, we’ll take a look at the method to determine if two variables are not equal to each other in C++ programming language.

Code snippet for Checking If Two Variables Are Not Equal

Here’s a simple C++ code snippet that checks if two variables are not equal to each other:

#include <iostream>
using namespace std;

int main() {  
   int a = 5;  
   int b = 10;  
  
   if(a != b) {  
      cout<< "Variables are not equal";
   } else {
      cout<< "Variables are equal";
   }  
   return 0;
}

This code will output “Variables are not equal” since 5 and 10 are not the same.

Code Explanation for Checking If Two Variables Are Not Equal

In the above code snippet, we begin by importing the iostream standard library file which allows for reading from standard input and writing to standard output.

We utilize ‘int’ to define two integer variables ‘a’ and ‘b’ with the values 5 and 10 respectively.

The core of this comparison is in the ‘if’ statement: if(a != b). The ‘! =’ operator is used as the not-equal-to operator that compares the two variables ‘a’ and ‘b’. If the condition (a not equal to b) is true, the program will execute the statements within the ‘if’ block, outputting “Variables are not equal” to the standard output.

On the other hand, if the condition (a not equal to b) is false (meaning a is equal to b), then the ‘else’ block will be executed and you’ll see “Variables are equal” printed to the console.

The program wraps up with the return statement, return 0, which is used to signify that the program has successfully executed without any errors.

c-plus-plus