If I do:
int i=3, j=10;
float f;
f=(i+j)/2;
so f won't get value 6.5 but 6.
But,
f=(i+(float)j)/10;//edited
would be f=6.5
.
What is the place where this temporary values are stored and why do we need to type-cast?
If I do:
int i=3, j=10;
float f;
f=(i+j)/2;
so f won't get value 6.5 but 6.
But,
f=(i+(float)j)/10;//edited
would be f=6.5
.
What is the place where this temporary values are stored and why do we need to type-cast?
f=(i+j(float))/10;
is incorrect; the type in a cast comes before its operand:
f=(i+(float)j)/10;
Anyway. When evaluating an arithmetic operator, if one operand is of a floating point type and the other is of an integer type, then the integer operand is converted to the floating point type and floating arithmetic is performed.
This is part of what are called the usual arithmetic conversions (you can find out more about those by searching Google, though MSDN has a simple explanation of what they are).
Where the temporary value is stored depends on the compiler and the computer. It's likely to be stored in a register since you're going to use it immediately, but it could be stored on the stack or somewhere else.
C defines "integral promotion" rules which determine what type will be used to carry out an integer calculation. An integer expression will be promoted to a type big enough to hold all values of the types in the expression, signed if possible, else unsigned. By casting one of the values to float you force the compiler to do floating-point promotion which promotes all of the integers to a suitable floating point type. You could also write 0.1 * (i+j)
in which case i+j
would be computed as an integer and then promoted to a floating point type to multiply with 0.1.