A cast is a conversion of a variable from one type to another data type. For example, if you want to store a value of type long into a simple integer, you need to cast long to int.
You can use the cast operator to explicitly convert a value from one type to another, as follows:
(type_name) expression
Consider the following example of dividing an integer variable by another integer variable using the cast operator to get a floating-point number:
#include <stdio.h> int main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %f/n", mean ); }
Copy the code
When the above code is compiled and executed, it produces the following results:
If you have a problem with C/C++ one item is a very enthusiastic one (● ‘◡’ ●).
Value of mean: 3.400000
Note here that the cast operator takes precedence over division, so the value of sum is first converted to double and then divided by count to get a value of type double.
Type conversions can be implicit, performed automatically by the compiler, or explicit, specified by using the cast operator. It is good programming practice to use cast operators whenever type conversions are needed.
Integer promotion
Integer promotion is the process of converting an integer type smaller than int or unsigned int to int or unsigned int. Look at the following example to add a character to int:
#include <stdio.h> int main() { int i = 17; Char c = 'c'. /* the ASCII value is 99 */ int sum; sum = i + c; printf("Value of sum : %d/n", sum ); }Copy the code
When the above code is compiled and executed, it produces the following results:
Value of sum : 116
In this case, sum is 116, because the compiler has been integer promoted to convert the value of ‘c’ to the corresponding ASCII value when the actual addition is performed.
Common arithmetic conversions
A common arithmetic conversion is to implicitly cast a value to the same type. The compiler first performs integer promotion, and if the operand types are different, they are converted to the highest-level type that occurs in one of the following levels:
Common arithmetic conversion does not apply to the assignment operator, logical operators && and | |. Let’s look at the following example to understand this concept:
#include <stdio.h> int main() { int i = 17; Char c = 'c'. /* ASCII value is 99 */ float sum; sum = i + c; printf("Value of sum : %f/n", sum ); }Copy the code
When the above code is compiled and executed, it produces the following results:
Value of sum: 116.000000
Here, C is first converted to an integer, but since the final value is a float, the usual arithmetic conversion is applied, where the compiler converts I and C to float and adds them together to get a float.