Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C

Learn step by step



C-Type Casting

Type casting is simply a way to convert a variable from one data type to another data type. Example, if you want to store a long value into an integer then you can convert the type int to long. You can convert values from one type to another explicitly using the type cast operator as:

(type_name) expression

By Considering the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation:


#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
} RUN

Note: The cast operator has precedence over division, so the value of sum is first converted to double and then it gets divided by count yielding a double value.

Type conversions can be implicit which is performed by the compiler automatically, or can be specified explicitly through the use of the cast operator. It's considered good programming practice to use the cast operator whenever type conversions are required.

Integer Promotion

It is the process by which values of integer type smaller than int or unsigned int are converted either to int or unsigned int. Let us consider an example of adding a character in an int:


#include <stdio.h>
main()
{
int p = 12;
char t = 't'; /* ascii value is 116 */
int sum;
sum = p + t;
printf("Value of sum : %d\n", sum );
} RUN

Here, value of sum is 128 because compiler is doing integer promotion and converting the value of 't' to ascii before performing addition operation.

Usual Arithmetic Conversion

They are implicitly performed to cast their values in a common type. Compiler firstly performs integer promotion, if the operands still have different types then they are converted to the type that appears highest in the following hierarchy:

The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators &&(AND) and ||(OR). Let's take following example to understand this concept:


#include <stdio.h>
main()
{
int p = 12;
char t = 't'; /* ascii value is 116 */
float sum;
sum = p + t;
printf("Value of sum : %f\n", sum );
} RUN



Related Videos