C – Type Casting functions


       Prev                                                                                              Next

  • Typecasting concept in C language is used to modify a variable from one date type to another data type. New data type should be mentioned before the variable name or value in brackets which to be typecast.

C type casting example program:

  • In the below C program, 7/5 alone will produce integer value as 1.
  • So, type cast is done before division to retain float value (1.4).
#include <stdio.h>
int main ()
{
    float x;
    x = (float) 7/5;
    printf("%f",x);
}

Output:

1.400000

Note:

  • It is best practice to convert lower data type to higher data type to avoid data loss.
  • Data will be truncated when higher data type is converted to lower. For example, if float is converted to int, data which is present after decimal point will be lost.

Inbuilt typecast functions in C:

  • There are many inbuilt typecasting functions available in C language which performs data type conversion from one type to another.
  • Click on each function name below for description and example programs.
S.no Typecast function Description
1 atof() Converts string to float
2 atoi() Converts string to int
3 atol() Converts string to long
4 itoa() Converts int to string
5 ltoa() Converts long to string


       Prev                                                                                              Next


Share this C programming language with your friends