HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
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.
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 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 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 .