Relational operators within C++ are operators utilized to assess the comparison between two specified values. These operators assist in decision-making and guiding the program’s execution flow in C++. This article will cover the definition of relational operators, the various types available, their application with conditional statements and logical operators, the purposes they serve, as well as any restrictions associated with relational operators in C++.
Relational Operators in C++ serve as symbols for comparing two values. These operators yield true (1) or false (0). If the condition holds true, true (1) is returned; if not, false (0) is returned. Relational operators seek to establish the relationship between the two operands. Additionally, they are referred to as comparison operators.
Types of Relational Operators in C++
There are six categories of relational operators in C++:
Operator Name
Symbol
Description
Syntax
Equal to
==
Checks if the two values are the same.
a == b
Not equal to
!=
Checks if the two values differ.
a != b
Greater than
>
Checks if the left value exceeds the right value.
a > b
Less than
<
Checks if the left value is smaller than the right value.
a < b
Greater than or equal
>=
Checks if the left value is either greater than or equal to the right value.
a >= b
Less than or equal
<=
Checks if the left value is either less than or equal to the right value.
a <= b
Let’s briefly explore each of these relational operators, accompanied by examples in C.
1. Equal to (==) Operator
The equal to (==) operator in C++ verifies whether two values are the same, returning true (1) if they are, and false (0) if they are not. This operator is frequently employed in conditional statements such as if statements.
function runCode3574() {
var code = editor3574.getSession().getValue();
jQuery(“#runBtn3574 i.run-code”).show();
jQuery(“.output-tab”).click();
jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data:
“““javascript
{
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action: “compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output3574”).html(“
"+data+"");
jQuery(".maineditor3574 .code-editor-output").show();
jQuery("#runBtn3574 i.run-code").hide();
}
})
}
function closeoutput3574() {
var code = editor3574.getSession().getValue();
jQuery(".maineditor3574 .code-editor-output").hide();
}
// Add event listeners to the buttons
document.getElementById("copyBtn3574").addEventListener("click", copyCodeToClipboard3574);
document.getElementById("runBtn3574").addEventListener("click", runCode3574);
document.getElementById("closeoutputBtn3574").addEventListener("click", closeoutput3574);
Result:
The snippet demonstrates that the equal to operator verifies if the integers a, b, and c with the values 10, 10, and 5 are identical and subsequently displays the result in the console.
2. Not Equal to (!=) Operator
The not equal to (!=) operator in C++ determines if two values differ and returns true (1) if they are not identical; otherwise, it indicates that the values are equal.
Syntax:
value1 != value2
Sample:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor90934.setValue(decodedContent); // Set the initial code
editor90934.clearSelection();
editor90934.setOptions({
maxLines: Infinity
});
function decodeHTML90934(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard90934() {
const code = editor90934.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor90934 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor90934 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode90934() {
var code = editor90934.getSession().getValue();
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output90934").html("
"+data+"");
jQuery(".maineditor90934 .code-editor-output").show();
jQuery("#runBtn90934 i.run-code").hide();
}
})
}
function closeoutput90934() {
var code = editor90934.getSession().getValue();
jQuery(".maineditor90934 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn90934").addEventListener("click", copyCodeToClipboard90934);
document.getElementById("runBtn90934").addEventListener("click", runCode90934);
document.getElementById("closeoutputBtn90934").addEventListener("click", closeoutput90934);
Result:
This snippet illustrates how the not equal to operator assesses that the given integers a and b are distinct. Initially, it returns true (1) since both a and b contain different values, but after modifying b to 10, it returns false (0).
3. Less Than (<) Operator
The less than (<) operator in C++ examines if the value on the left is inferior to the value on the right and subsequently yields true (1) if the condition holds, or false (0) otherwise.
Syntax:
value1 < value2
Sample:
Cpp
Code Copied!
``````html
var isMobile = window.innerWidth “”);
editor87956.setValue(decodedContent); // Establish the default text
editor87956.clearSelection();
editor87956.setOptions({
maxLines: Infinity
});
function decodeHTML87956(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard87956() {
const code = editor87956.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
jQuery(“.maineditor87956 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor87956 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function closeoutput87956() {
var code = editor87956.getSession().getValue();
jQuery(“.maineditor87956 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn87956”).addEventListener(“click”, copyCodeToClipboard87956);
document.getElementById(“runBtn87956”).addEventListener(“click”, runCode87956);
document.getElementById(“closeoutputBtn87956”).addEventListener(“click”, closeoutput87956);
Result:
The script demonstrates how the less-than operator verifies if the left operand is smaller than the right operand. Initially, it evaluates x = 5 and y = 10, and subsequently checks after modifying x to 15, outputting the results to the console.
4. Greater Than (>) Operator
The greater than (>) operator in C++ assesses if the left operand exceeds the right operand, returning true (1) when the condition is satisfied; otherwise, it yields false (0).
Syntax:
value1 > value2
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth “”);
editor90142.setValue(decodedContent); // Establish the default text
editor90142.clearSelection();
editor90142.setOptions({
maxLines: Infinity
});
function decodeHTML90142(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard90142() {
const code = editor90142.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
jQuery(“.maineditor90142 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor90142 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function closeoutput90142() {
var code = editor90142.getSession().getValue();
jQuery(“.maineditor90142 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn90142”).addEventListener(“click”, copyCodeToClipboard90142);
document.getElementById(“runBtn90142”).addEventListener(“click”, runCode90142);
document.getElementById(“closeoutputBtn90142”).addEventListener(“click”, closeoutput90142);
Result:
The snippet illustrates how the greater-than operator evaluates whether the left operand exceeds the right operand. Initially, it checks a = 25 and y = 20, then reassesses after altering the value of b to 15 and logs the results to the console.
5. Less Than or Equal To (<=) Operator
The less than or equal to (<=) operator in C++ verifies if the left operand is either less than or equal to the right operand, returning true (1) if the predicate holds; otherwise, it yields false (0).
Syntax:
value1 <= value2
Sample:
Cpp
Code Copied!
var isMobile = window.innerWidth “);
editor88587.setValue(decodedContent); // Set the default text
editor88587.clearSelection();
editor88587.setOptions({
maxLines: Infinity
});
function decodeHTML88587(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard88587() {
const code = editor88587.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
data: {
language: “cpp”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output88587”).html(“
"+data+"");
jQuery(".maineditor88587 .code-editor-output").show();
jQuery("#runBtn88587 i.run-code").hide();
}
})
}
function closeoutput88587() {
var code = editor88587.getSession().getValue();
jQuery(".maineditor88587 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn88587").addEventListener("click", copyCodeToClipboard88587);
document.getElementById("runBtn88587").addEventListener("click", runCode88587);
document.getElementById("closeoutputBtn88587").addEventListener("click", closeoutput88587);
Result:
The snippet illustrates how the less than or equal to operator evaluates two integers, x and y, subsequently logging the output by comparing different values of x.
6. Greater Than or Equal To (>=) Operator
The greater than or equal to operator (>=) in C++ assesses whether the left operand is greater than or equal to the right operand, returning true (1) if so; otherwise, it yields false (0).
Syntax:
value1 >= value2
Sample:
Cpp
Code Copied!
``````html
var isMobile = window.innerWidth ");
editor22949.setValue(decodedContent); // Initialize the text
editor22949.clearSelection();
editor22949.setOptions({
maxLines: Infinity
});
function decodeHTML22949(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard22949() {
const code = editor22949.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor22949 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor22949 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode22949() {
var code = editor22949.getSession().getValue();
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output22949").html("
"+data+"");
jQuery(".maineditor22949 .code-editor-output").show();
jQuery("#runBtn22949 i.run-code").hide();
}
});
}
function closeoutput22949() {
var code = editor22949.getSession().getValue();
jQuery(".maineditor22949 .code-editor-output").hide();
}
// Assign event listeners to the buttons
document.getElementById("copyBtn22949").addEventListener("click", copyCodeToClipboard22949);
document.getElementById("runBtn22949").addEventListener("click", runCode22949);
document.getElementById("closeoutputBtn22949").addEventListener("click", closeoutput22949);
Output:
This code demonstrates how the greater than or equal to operator evaluates two integers, a and b, and subsequently displays the output by verifying with various values of a.
Relational Operators with Conditional Constructs in C++
The relational operators are utilized alongside the conditional constructs to direct the execution path of C++ programs based on comparisons.
Syntax of if-else with Relational Operators:
if (condition using relational operator) {
// code executes if condition is true
}
else {
// code executes if condition is false
}
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor97193.setValue(decodedContent); // Initialize the text
editor97193.clearSelection();
editor97193.setOptions({
maxLines: Infinity
});
function decodeHTML97193(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard97193() {
const code = editor97193.getValue(); // Obtain code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor97193 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor97193 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode97193() {
var code = editor97193.getSession().getValue();
function closeoutput97193() {
var code = editor97193.getSession().getValue();
jQuery(".maineditor97193 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn97193").addEventListener("click", copyCodeToClipboard97193);
document.getElementById("runBtn97193").addEventListener("click", runCode97193);
document.getElementById("closeoutputBtn97193").addEventListener("click", closeoutput97193);
Output:
The code illustrates how relational operators are employed within if-else constructs to assign grades to students based on their scores.
Relational Operators Combined with Logical Operators in C++
Relational operators assess each value, while logical operators amalgamate or negate the results from multiple expressions to create intricate conditions.
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor82573.setValue(decodedContent); // Set the default text
editor82573.clearSelection();
editor82573.setOptions({
maxLines: Infinity
});
function decodeHTML82573(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard82573() {
const code = editor82573.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor82573 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor82573 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode82573() {
var code = editor82573.getSession().getValue();
function closeoutput82573() {
var code = editor82573.getSession().getValue();
jQuery(".maineditor82573 .code-editor-output").hide();
}
// Associate event listeners with the buttons
document.getElementById("copyBtn82573").addEventListener("click", copyCodeToClipboard82573);
document.getElementById("runBtn82573").addEventListener("click", runCode82573);
document.getElementById("closeoutputBtn82573").addEventListener("click", closeoutput82573);
Output:
The snippet demonstrates how relational operators evaluate age and scores, while the logical AND operator verifies that the conditions meet the requirements before eligibility is granted.
Application of Relational Operators in C++
Relational operators are utilized to assess integer data types to verify conditions such as equality, greater than, and less than.
They are capable of comparing float and double values. However, due to potential precision errors, direct equality comparisons (==) may yield unreliable results.
These operators compare characters according to their ASCII values.
Relational operators can also compare memory addresses held in pointers.
In user-defined types, relational operators may be overloaded to compare objects based on specific criteria.
They work in tandem with conditional statements to direct the program's flow of execution.
Drawbacks of Relational Operators in C++
Relational operators are inadequate for complex logic without being combined with logical operators.
Using relational operators on floating-point numbers may cause inaccuracies due to precision concerns.
These operators do not function with custom data types unless explicitly overloaded.
Attempting to compare incompatible data types with relational operators results in compilation errors.
Relational operators do not validate value ranges directly, thus necessitating manual construction of compound conditions.
“““html
Conclusion
In C++, comparison operators serve to evaluate two values and influence the program’s flow based on certain conditions. These operators also aid in making decisions while comparing various data types such as integers, characters, and user-defined structures. Consequently, by grasping their categories, limitations, applications, and how these operators collaborate with logical operators, you can effectively utilize comparison operators to assess values within C++ programming.
Comparison Operators in C++ – FAQs
Q1. What are comparison operators in C++?
Comparison operators are utilized for evaluating two values.
Q2. Is it possible to use comparison operators with strings?
Yes, comparison operators can be applied with strings as they assess strings in alphabetical order.
Q3. Is == dependable for floating-point comparison?
No, it is not dependable due to potential precision concerns.
Q4. Am I able to compare custom objects?
Yes, comparing custom objects is permissible in your code.
Q5. What distinguishes == from =?
The distinction between == and = is that == verifies equality, while = assigns values.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.