Latest web development tutorials

C casts

Casts the variable is converted from one type to another data type. For example, if you want to store the value of a long type to a simple integer, you need to type long cast to type int. You can use thecast operator to explicitly put values from one type into another type, as follows:

(type_name) expression

Consider the following examples, the use of mandatory conversion operator to an integer variable by another integer variable, get a float:

#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

To note here is the cast operator takes precedence over the division, so the value of thesum is first converted to a double,then divide count, get a value of type double of.

Type conversions can be implicit, performed automatically by the compiler, it can be explicit, specified by using thecast operator.In programming, there is a need to spend time type conversion cast operator, is a good programming practice.

Integral promotion

Refers to integral promotion is less thanint or unsigned intinteger type is converted tointorunsigned intprocess. Consider the following example, add a character in an 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 produces the following results:

Value of sum : 116

Here, sum of the value 116, because the compiler has been integral promotion when performing the actual addition operation, the 'c' value converted to the corresponding ascii value.

Usual arithmetic conversions

Usual arithmetic conversions are implicitly cast to the value of the same type.The compiler first performsinteger lifting, if the operands of different types, they are converted to the following hierarchy appears highest level Type:

Usual Arithmetic Conversion

Usual arithmetic conversions do not apply to the assignment operator, logical operators && and ||. Let's look at the following examples 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 an integer, but due to the last value is double type, so the usual arithmetic conversions are applied, the compiler will i and c is converted to float, and put them together to get a floating-point number .