Type Casting in C Language
In C, type casting refers to convert the data type of one variable to another data type. In some cases, compiler will automatically convert one data type to another without the programmer's intervention if it makes sense. For example, if we assign an integer value to a float variable, the compiler will convert the int to float. The cast operator allows us to make this type of conversion explicit when type casting wouldn't normally happen.
Type casting in the C language can be classified into the following two types:
• Implicit Type Casting
• Explicit Type Casting
1. Implicit Type Casting - Implicit Type Casting happens when compiler automatically convert one data type to another not losing its actual meaning without the programmer's intervention. If we are doing a conversion on two different data types then the lower data type is automatically converted into a higher data type.
Example 1 : Implicit Type Conversion #include<stdio.h> void main() { int count = 4; float total = 12.4, avg; avg = total / count; printf("Avg. : %f\n", avg ); } Output: Avg. : 3.1 Example 2 : Char to Int Conversion #include<stdio.h> void main() { int num = 7; char c = 'U'; int add; add = num + c; printf("Value of add : %d\n", add); } Output: Value of add : 90In the above example, the variables 'a' and 'b' are declared inside the function main(). So, they can be used only inside main() function and not in add() function.
2. Explicit Type Casting - Explicit Type Casting is a process of converting a higher data type value into a lower data type using cast operator by the programmer.
Example 1 : Explicit type casting from double to int #include<stdio.h> void main() { double d = 12345.6789; int i; i = (int)d; //Explicit casting from double to int printf("i = %d, d = %lf", i, d); } Output: i = 12345, d = 12345.678900 Example 2 : Explicit type casting from int to char #include<stdio.h> void main() { int x; for(x=97; x<=122; x++) { printf("%c ", (char)x); } } Output: a b c d e f g h i j k l m n o p q r s t u v w x y z
Inbuilt Type Casting Functions
There are many inbuilt type casting functions available in C programming language, which performs type conversion from one data type to another.
Functions | Description | Syntax |
atof() | Converts string to float | double atof(const char* string) |
atoi() | Converts string to int | int atoi(const char * str) |
atol() | Converts string to long | long int atol(const char * str) |
itoa() | Converts int to string | char * itoa(int value, char * str, int base) |
ltoa() | Converts long to string | char *ltoa(long n, char *str, int base) |