Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.
(Redirected from Type conversion)

Casting in programming is the process of converting a value (often stored in a variable) from one data type to another.

This changes what methods we can call on the value.

The syntax to cast a value varies a lot by the programming language.

C-style casting is done like this:

(type)value

For example, to cast an integer to a float, we would do:

int number = 4;
float fnumber = (float)4;
printf("%f", fnumber); // 4.0

Lossy type conversion

edit edit source

Sometimes, while a value could fit in the source data type, it can't properly fit into the target data type. For example, a decimal float into an integer.

In this case, the program may either return an error, throw an exception, or the value may be rounded or truncated. In the case of casting an integer into a floating point number, the value is truncated:

float f = 3.14;
int i = (float)f;
printf("%d", i); // 3