Results of Comparison Operations in C and C++
In this tutorial, we will explore comparison operators and how the system should compare an incoming value supplied as a context parameter to a given value or range of values. A nested expression can be used to supply the test parameter in addition to a context parameter. Make use of the sizeof() function to compare the results of operations performed in C and C++.
What is sizeof() Function:
The Sizeof() operator in C/C++ is a machine-dependent characteristic that varies from compiler to compiler. It might be referred to as byte-specific functionality. By providing the variables' byte and size as well as the number of bytes they occupy, it helps with the memory allocation of variables. Only the precise size of a variable type may be ascertained using the sizeof() method in C/C++ programming. Because of its flexibility and versatility, it is very helpful in the implementation and development of portable programs.
What are Comparison Operations?
Comparison operations define how the system should evaluate an incoming value provided as a context parameter against a specified value or value range. The test parameter can be provided via a nested expression in addition to being supplied by a context parameter.
Let's look at a few C and C++ examples to better grasp the contrasting outcomes of comparison operations in C and C++.
C Program:
In the C programming language, the ultimate outcome of comparison operations has the data type int. Consider the instance that follows.
#include<stdio.h>
int main ()
{
// Declaring and initializing two variables
int i = 30, j = 22;
printf ( "%d \n", sizeof ( i == j ) );
printf ( "%d \n", sizeof ( i < j ) );
return 0;
}
Output:
4
4
Statement: The result is presented as 4 in C because the result of comparison operations uses an int data type (the size of Integer).
C++ Program:
The outcome of comparison operations in C++ is of the data type bool. Consider the instance that follows.
#include<iostream>
using namespace std;
int main ()
{
// Declaring and initializing two variables
int i = 30, j = 22;
cout << sizeof ( i > j ) << "\n";
cout << sizeof ( i == j );
return 0;
}
Output:
1
1
Statement: The outcome of comparison operations in C++ has a boolean data type, hence the result is presented as 1. (the size of boolean).
Why are Comparison Operations outcomes different in C and C++?
In C, the outcome of a comparison operation possesses int data type, while in C++, the outcome of a comparison operation possesses bool data type.
Conclusion
We have covered the outcomes of comparison operations in C and C++ in great detail in this tutorial. The article describes how comparison operators' results can vary in C and C++.