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 b = 3.14;
a = (int) b; /* a is 3 */

Let's use a quick reworking of the temperature example to demonstrate conversion.

To convert variables from one type to another

1.
Open temperature2.c (Script 3.3) in your text editor or IDE.

2.
Change the printf() line to read as follows (Script 3.5):

printf ("%d degrees Celsius is %d
 degrees Fahrenheit.
", (int)
 temp_c, (int) temp_f);

Script 3.5. C allows you to, and can automatically, convert values from one type to another.


In the original example, the numbers were displayed as decimals. To display them as integers, without having to change the original variable declarations or arithmetic, use type casting when feeding the values to the printf() function. Because the types are being changed, the signifiers within the function are also switched (from %0.1f to %d).

3.
Save the file as temperature3.c.

4.
Compile, debug, and run the application (Figure 3.9).

Figure 3.9. To display the numbers as integers rather than floats, type conversion is used (compare with Figure 3.5).


✓ Tips

  • As you may have already experienced, feeding the printf() function the wrong signifier for a type normally leads to bizarre results. For example (Figure 3.10):

    printf ("Not a float: %f; not an 
     integer: %d", 8, 345.09);
    

    Figure 3.10. Mismatching a printf() signifier to a value type will have unusual consequences.

  • Type casting has its own rules of precedence, but they're cumbersome and not worth memorization.

  • If the truncation that occurs when converting floats to integers annoys you, you can round the value, like so:

    printf ("%d degrees Celsius is %d
     degrees Fahrenheit.
    ", (int)
     (temp_c + 0.5), (int) (temp_f
     + 0.5));
    

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset