Type Casting in C
Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a ‘long’ value into a simple integer then you can type cast ‘long’ to ‘int’. You can convert the values from one type to another explicitly using the cast operator as follows
//syntex type casting
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation −
Typecasting Flow diagram
Example
#include <stdio.h>
main() {
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
Output
Value of mean : 3.400000
Example
# include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
Output
Value of sum : 116
What is the purpose of type casting?
Typecasting. Typecasting, or type conversion, is a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function.
When should type cast be used?
When should a type cast be used? in C programming languageThere are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly. If you have read FAQ II.12, the following listing should look familiar.
What is casting in programming?
Well, all casting really means is taking an Object of one particular type and “turning it into” another Object type. This process is called casting a variable. This topic is not specific to Java, as many other programming languages support casting of their variable types.