Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Cast operator demo

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);

  exit(0);
}

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

 
 
  Published under free license. Design by Interspire