Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator for typecasting which is denoted by (type).syntax :
c(type) expression
Types of Type Casting in C
Implicit Type Casting (Type Coercion): Implicit type casting is done automatically by the C compiler when you perform operations involving different data types. The compiler converts one or more operands to a common data type before performing the operation. This is also known as "type coercion." For example:
In the above example, the integer a is implicitly cast to a double before performing the addition operation.cint a = 5; double b = 2.5; double result = a + b; // Implicit type casting of 'a' to doubleExplicit Type Casting: Explicit type casting allows you to manually convert a value from one data type to another by using casting operators.
Here's an example of explicit type casting using C-style casting:
In this example, the value of b is explicitly cast to an integer, resulting in the value 2 being assigned to a.It's important to note that type casting should be used with caution because it can lead to data loss or unexpected behavior if not done correctly. You should be aware of the potential loss of data when converting from a wider data type to a narrower data type.cdouble b = 2.5; int a = (int)b; // Explicit type casting of 'b' to intHere are a few more examples of explicit type casting:
In the above examples, explicit type casting is used to convert a double to an int and an int to a char.cdouble pi = 3.14159; int truncatedPi = (int)pi; // Explicitly cast double to int, truncating the decimal part int x = 65; char ch = (char)x; // Explicitly cast int to char, converting the ASCII value to a character
0 Comments