C Type casting

A cast is to convert a variable from one type to another data type. For example, if you want to store a long value into a simple integer, you need to cast the long type to int type. You can useCast operatorto explicitly convert a value from one type to another, as shown below:

(type_name) expression

Please look at the following example, using a cast operator to divide one integer variable by another integer variable to obtain a floating-point number:

Example

#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

Note here that the precedence of the cast operator is higher than division, sosumThe value of ... is first converted todoubletype, then divide by count, yielding a value of type double.

Type conversion can be implicit, performed automatically by the compiler, or explicit, by usingCast operatorto specify. In 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 thanintorunsigned intinteger types tointorunsigned intthe process. Please look at the following example, adding a character to an int:

Example

#include <stdio.h> int main() { int i = 17; char c = 'c'; /*ASCII value is 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 performed integer promotion, converting the value of 'c' to its corresponding ASCII value during the actual addition operation.

Common arithmetic conversions

Usual arithmetic conversionsis to implicitly cast values to the same type. The compiler first performsInteger promotionif the operand types are different, they are converted to the type of the highest level that appears in the following hierarchy:

Usual Arithmetic Conversion

The usual arithmetic conversions do not apply to assignment operators, or to the logical operators && and ||. Let's look at the following example to understand this concept:

Example

#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 ); }

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 of type float, the usual arithmetic conversions are applied. The compiler converts i and c to floating point, adds them, and obtains a floating-point number.

other extensions