next up previous contents index
Next: Storage-class specifiers (advanced) Up: Variables Previous: Declarations and scope   Contents   Index


Automatic conversions and casts

Once variables have been declared, they can be manipulated and combined in various ways. Exactly which operators may be applied to a variable depends on its type: for example all the numerical types support the usual arithmetic operations (addition, multiplication etc.) but only integer types support the modulus operator, %.

Sometimes you need to convert from one type to another, for example when assigning an int to a floating-point type. It is clear what the result of such a conversion should be, and C is prepared to convert between most pairs of related types automatically:

  
int   a = 6;
float b = 3.5;
int   c;

c = b;  /*  ok, b gets rounded towards zero, so c=3  */
b = a;  /*  ok, b becomes the real number 6  */

To convert between types for which an automatic conversion does not exist, or to force a conversion at a convenient moment, use a cast:

  
int   n = 4;
int   m = 6;
float n_over_m;

n_over_m = n/m;            /*  yields 0  */
n_over_m = n/ (float)m;    /*  (cast m to a float) yields 0.66666 etc.  */
Without the cast, n/m will be evaluated using integer division (which returns the quotient, discarding the remainder). The cast forces m to be converted to a float, after which n is automatically converted to a floating-point type and the division is done floating-point.


next up previous contents index
Next: Storage-class specifiers (advanced) Up: Variables Previous: Declarations and scope   Contents   Index
CATAM admin 2010-02-23