Casting: Difference between revisions
From Coderwiki
More actions
new |
(No difference)
|
Latest revision as of 12:09, 11 August 2025
Casting in programming is the process of converting a value (often stored in a variable) from one data type to another.
Syntax
edit edit sourceThe 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 sourceSometimes, 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