Tuesday, 3 February 2015

C - Type casting

C - Type casting
·         Type casting is a way to convert a variable from one data type to another data type.
·         For example, if we want to store a long value into a simple integer then we can type cast long to int.
·         We can convert values from one type to another explicitly using the cast operator as follows:
(type_name) expression

C type casting example program:

  • In the below C program, 7/5 alone will produce integer value as 1. Truncates the decimal value.
  • To retain decimal value, type cast is done before division (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.
Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy:
long bouble

double
 


float

unsigned long long

long long
 


unsigned long

long

unsigned int

int
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take following example to understand the concept:
#include <stdio.h>

main()
{
   int  i = 17;
   char c = 'c'; /* ascii value is 99 */
   float sum;

   sum = i + c;
   printf("Value of sum : %f\n", sum );

}
When the above code is compiled and executed, it produces the following result:
Value of sum : 116.000000
Here, it is simple to understand that first c gets converted to integer but because final value is double, so usual arithmetic conversion applies and compiler convert i and c into float and add them yielding a float result.

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.

S.no
Typecast function
Description
1
atof()
Converts string to float
2
Converts string to int
3
Converts string to long
4
Converts int to string
5
Converts long to string

No comments:

Post a Comment