Variable Conversion

Over the course of this chapter you've seen many ways of working with the various number types. One last technique to be addressed is that of variable conversion: changing the value of a variable from one type (say, float) to another (integer).

C will automatically convert values to match types; for example:

int a;
float b = 3.14;
a = b; /* a is 3 */
b = a; /* b is 3.0 */

In simplest terms, this means that the decimal value is dropped when converting from a float to an integer and that a 0 is added when going the other way.

You can also manually convert a value from one type to another, a process called type casting. To do so, precede the value being converted with the new type in parentheses. For example:

 int a; float ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.