Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the operands of an operator needs to be of the same type?

Tags:

c++

types

casting

If I have something like this:

int i = 123;
float f = 123.1;

if (f > i) {} else {}

The i will be promoted to a float and the comparison will become if (float > float). My question is why does the int variable needs to be promoted to a float in the first place, Is it because its easier for the computer to compare two plain numbers than trying to figure out what the bits of each number represent and then compare that?

like image 248
John Avatar asked Jan 18 '15 07:01

John


1 Answers

Because "There are no numbers". Computers don't compare numbers, and don't work with numbers. They work with, and compare, bit patterns.

The fact bit patterns represent numbers is due to the "encoding" we use to represent numbers as bit patterns. And once we choose an encoding, operations on numbers become operations on bit patterns. And once we choose another encoding, same operations on numbers become other operations on bit patterns.

Now, if you have 10 possible way to represent numbers, you should support 100 possible ways to do binary operations (or even 1000, if you also want to consider the result!).

Since this cannot scale, you have to reduce. And the simpler way to reduce is to eliminate similar things by splitting them into parts: first convert all all numbers to go into a common encoding, then operate on that encoding and eventually convert the result back to the desired one.

This is essentially due to the fact that operation on numbers having a same encoding can be implemented easily since same rules apply everywhere, and this can be done by reusing the same circuitry.

But for this to work, the "common format" must be chosen so that both the operands can be represented. And representing an int into a float has more chances to succeed than representing a float into an int.

like image 153
Emilio Garavaglia Avatar answered Oct 30 '22 00:10

Emilio Garavaglia