C Programming Explicit Type Cast Operator
Last modified by Microchip on 2023/11/09 09:06
Earlier, we cast a literal to type float by entering it as: 4.0f
We can cast the variable instead by using the cast operator: (type)variable
Example: Integer Divide
1
2
3
4
2
3
4
int x = 10;
float y;
y = x / 4;
float y;
y = x / 4;
Floating Point Divide
1
2
3
4
2
3
4
int x = 10;
float y;
y = (float)x / 4;
float y;
y = (float)x / 4;
The typecast used in the code fragment on the right temporarily converts the variable x into a float for the duration of the operation. This forces the operation to use float as its type, yielding the desired result.