Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the general rules for comparing different data types in C?

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?

like image 487
Gene Avatar asked Jul 09 '11 18:07

Gene


People also ask

Can we compare different data types in C?

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.

What are the different data types in C?

There are four basic data types in C programming, namely Char, Int, Float, and Double.

What are the 5 data types in C?

character, integer, floating-point, double. Array, structure, union, etc.

How do you compare data types in C++?

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.


1 Answers

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.

like image 137
Michael Koval Avatar answered Oct 02 '22 15:10

Michael Koval