Type Casting in C
Typecasting is
converting one data type into another one. It is also called as data conversion
or type conversion. It is one of the important concepts introduced in 'C'
programming.
'C' programming
provides two types of type casting operations:
- Implicit type casting
- Explicit type casting
Implicit
type casting:
Implicit type conversion happens automatically when a value is copied to
its compatible data type. During conversion, strict rules for type conversion
are applied. If the operands are of two different data types, then an operand
having lower data type is automatically converted into a higher data
type. Converting from smaller data type into larger data type is also
called as type promotion.
The implicit type conversion always happens with the compatible data
types.
Example 1:
int a = 100;
double b = 12.5;
a + b;
Here one operand is of type int and other is of
type double. The variable ‘a’ will be converted
to double and the result of the overall operation will be
a double i.e 112.500000.
Example 2:
char ch = 'a';
int a = 10;
a + c;
Here, char will be converted to int before any operation and the result
of the overall operation will an int. Since the integral value of ch is 97 (i.e
ASCII value of the character 'a' ). Hence, 97 + 10 = 107.
Explicit type
casting
There are some scenarios where automatic type conversion is not possible.
in such cases explicit type conversion is used. It requires a type casting
operator. The general syntax for type casting operations is as follows:
(type-name) expression
Here,
- The type name is the standard
'C' language data type.
- An expression can be a
constant, a variable or an actual expression.
Example:
#include<stdio.h>
int main()
{
float a = 1.2;
//int b = a;
//Compiler will throw an error for this
int b = (int)a + 1;
printf("Value of a is %f\n", a);
printf("Value of b is %d\n",b);
return 0;
}
output:
Value of a is 1.200000
Value of b is 2
No comments:
Post a Comment