This might be very basic but I got very curious what the reason is.
When dealing with different types of operations such as multiplication and division with data by different types (int, float etc) what decides which datatype that gets picked?
For example, if I do the following:
float a = 5 / 10;
I will get “0” as result since the 5 and the 10 are temporarily stored in an int where we do the division, and then we put it in a float. Right?
But if we instead do:
float a = (float)5 / 10;
We get 0.5 instead.
How does the decision making look when float is prefered over int in this case in C?
Take a look at this snippet.
5and10are represented as integers to C (and Java and C++ and Python 2.x) by default. They’re not specified to be stored in any other way; that is to say, they don’t match the appearance of a floating-point type. Integer division results in truncation, so you’ll get the value 0 every time.Now, regarding the second snippet:
…C (or Java or C++ or Python 2.x) will interpret it as:
Because the floating-point value is of a higher rank than an integer, it will promote the integer to a float. This is known as type promotion. You can read a bit about it here.