May 11, 2021 C
Casting a type conversion is the conversion of a variable from one type to another. F or example, if you want to store a long type of value into a simple integer, you need to cast the long type to an int type. You can use the cast type conversion operator to explicitly convert values from one type to another, as follows:
(type_name) expression
Look at the following example, which uses a cast type conversion operator to divide an integer variable by another to get a floating point:
#include <stdio.h>
int main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
When the above code is compiled and executed, it produces the following results:
Value of mean : 3.400000
It is important to note here that the cast type conversion operator takes precedence over division, so the value of sum is first converted to double type and then divided by count to get a value of type double.
Type conversions can be implicit, automated by the compiler, or explicit, specified by using the cast type conversion operator. It is a good programming habit to use the cast type conversion operator when programming is necessary.
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 and add a character to the int:
#include <stdio.h>
int main()
{
int i = 17;
char c = 'c'; /* ascii 值是 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following results:
Value of sum : 116
Here, the value of sum is 116, because the compiler has an integer boost that converts the value of 'c' to the corresponding ascii value when performing the actual addition operation.
A common arithmetic conversion is to implicitly cast values to the same type. The compiler first performs integer promotions, which are converted to the highest-level types that appear in the following levels if the operator types are different:
Common arithmetic conversions do not apply to assignment operators, logical operators, and ||. Let's look at the following example to understand the concept:
#include <stdio.h>
int main()
{
int i = 17;
char c = 'c'; /* ascii 值是 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
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 last value is double, a common arithmetic conversion is applied, and the compiler converts i and c to floating-point patterns and adds them up to a floating-point number.