Node:Cast operator demo, Previous:The cast operator, Up:The cast operator

Cast operator demo

The following is an example of how to use the cast operator in C code. It also shows how to use an integer variable to store a character value.

/*                                                 */
/* Demo of Cast operator                           */
/*                                                 */

#include <stdio.h>

int main()               /* Use int float and int */
  float my_float;
  int my_int;
  int my_ch;

  my_float = 75.345;
  my_int = (int) my_float;
  my_ch = (int) my_float;
  printf ("Convert from float my_float=%f to my_int=%d and my_ch=%c\n",
    my_float, my_int, my_ch);

  my_int = 69;
  my_float = (float) my_int;
  my_ch = my_int;
  printf ("Convert from int my_int=%d to my_float=%f and my_ch=%c\n",
    my_int, my_float, my_ch);

  my_ch = '*';
  my_int = my_ch;
  my_float = (float) my_ch;
  printf ("Convert from int my_ch=%c to my_int=%d and my_float=%f\n",
    my_ch, my_int, my_float);


Here is the sort of output you should expect (floating point values may differ slightly):

Convert from float my_float=75.345001 to my_int=75 and my_ch=K
Convert from int my_int=69 to my_float=69.000000 and my_ch=E
Convert from int my_ch=* to my_int=42 and my_float=42.000000