Lets say I have the following scenarios:
int i = 10;
short s = 5;
if (s == i){
do stuff...
} else if (s < i) {
do stuff...
}
When C does the comparison does it convert the smaller data type, in this case short to int or does it convert the data type on the right to the data type on the left? In this case int to short?
As a general rule, C will not compare two values if they are not the same type and will never implicitly convert a variable to a type with less precision. In your sample code, the short is promoted to an int , which is equivalent to writing: Show activity on this post.
There are four basic data types in C programming, namely Char, Int, Float, and Double.
character, integer, floating-point, double. Array, structure, union, etc.
In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.
As a general rule, C will not compare two values if they are not the same type and will never implicitly convert a variable to a type with less precision. In your sample code, the short
is promoted to an int
, which is equivalent to writing:
int i = 10;
short s = 5;
if ((int)s == i){
do stuff...
} else if ((int)s < i) {
do stuff...
}
This will do exactly what you expect, but the same is not true of signed/unsigned comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With