Converting an expression from one type to another is known as type casting or type conversion. This can be done either implicitly by the compiler or explicitly with code.
Implicit Conversions
An implicit conversion is performed automatically by the compiler when an expression needs to be converted into one of its compatible types. For example, any conversions between the primitive data types can be done implicitly.
long l = 5; /* int -> long */
double d = l; /* long -> double */
These implicit conversions can also take place within an expression, allowing you to mix different primitive types together. When types of different sizes are involved, the result will be of the larger type, so an int and double will produce a double value.
double d = 5 + 2.5; /* int -> double */
Implicit conversions of primitive types can be further grouped into two kinds: promotion and demotion. Promotion occurs when an expression gets implicitly converted into a larger type, and demotion occurs when converting an expression to a smaller type.
/* Promotion */
long l = 5; /* int promoted to long */
double d = l; /* long promoted to double */
/* Demotion */
int i = 10.5; /* warning: possible loss of data */
char c = i; /* warning: possible loss of data */
Because a demotion can result in the loss of information, these conversions generate a warning on many compilers. If the potential information loss is intentional, the warning can be suppressed by using an explicit cast.
Explicit Conversions
An explicit cast is performed by placing the desired data type in parentheses to the left of the expression that needs to be converted.
int i = (int)10.5; /* double demoted to int */
char c = (char)i; /* int demoted to char */
Keep in mind that casting a variable only makes it temporarily evaluate as a different type; it does not change the variable’s underlying type.