C cast


Forced type conversion is to convert a variable from one type to another data type. For example, if you want to store a long value in a simple integer, you need to cast the long to an int. You can use the cast operator to explicitly convert a value from one type to another, as shown below:

(type_name) expression

See the following example, using coercion The type conversion operator divides one integer variable by another integer variable, resulting in a floating point number:

#include <stdio.h>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 should be noted here that the priority of the cast operator is greater than that of division, so the value of sum is first converted to type double, and then divided by count to obtain a type of double value.

Type conversion can be implicit, performed automatically by the compiler, or explicit, specified by using the cast operator. When programming, it is a good programming habit to use the cast operator whenever type conversion is needed.

Integer promotion

Integer promotion refers to converting integer types smaller than int or unsigned int to int or unsigned int process. Look at the following example, adding a character to int:

#include <stdio.h>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 will produce the following results:

Value of sum : 116

Here, the value of sum is 116, because the compiler performs integer promotion and converts the value of 'c' to the corresponding ascii value when performing the actual addition operation.

Commonly used arithmetic conversions

Commonly used arithmetic conversionsimplicitly coerce values ​​into the same type. The compiler first performs integer promotion. If the operand types are different, they are converted to the highest level type occurring in the following hierarchy:

1056.png

Common arithmetic conversions do not apply For assignment operators, logical operators && and ||. Let us see the following example to understand this concept:

#include <stdio.h>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 integer, but since the final value is of type double, the usual arithmetic conversions are applied, and the compiler converts i and c to floating point types and adds them to get a floating point number.