In C++, comparison operators are used to compare two values and produce a boolean result (true or false). Here are the primary comparison operators:
-
Equal to (
==): Checks if two values are equal.if (a == b) { /* true if a is equal to b */ } -
Not equal to (
!=): Checks if two values are not equal.if (a != b) { /* true if a is not equal to b */ } -
Less than (
<): Checks if the left value is less than the right value.if (a < b) { /* true if a is less than b */ } -
Less than or equal to (
<=): Checks if the left value is less than or equal to the right value.if (a <= b) { /* true if a is less than or equal to b */ } -
Greater than (
>): Checks if the left value is greater than the right value.if (a > b) { /* true if a is greater than b */ } -
Greater than or equal to (
>=): Checks if the left value is greater than or equal to the right value.if (a >= b) { /* true if a is greater than or equal to b */ }
Example Code:
#include <iostream>
int main() {
int a = 5;
int b = 10;
std::cout << "a == b: " << (a == b) << std::endl; // false
std::cout << "a != b: " << (a != b) << std::endl; // true
std::cout << "a < b: " << (a < b) << std::endl; // true
std::cout << "a <= b: " << (a <= b) << std::endl; // true
std::cout << "a > b: " << (a > b) << std::endl; // false
std::cout << "a >= b: " << (a >= b) << std::endl; // false
return 0;
}
Output:
a == b: 0
a != b: 1
a < b: 1
a <= b: 1
a > b: 0
a >= b: 0
Summary:
Comparison operators in C++ allow you to compare values and produce boolean results, which are essential for making decisions in your code. If you have further questions or need clarification, feel free to ask!
