typecasting in C

How typecasting plays an important role in C

C allows programmers to perform typecasting by placing the type name in parentheses and placing this in front of the value.

For instance

float a;
a = (float)5 / 3;

gives result as 1.666666 . This is because the integer 5 is converted to floating point value before division and the operation between float and integer results in float.

From the above it is clear that the usage of typecasting is to make a variable of one type, act like another type for one single operation. So by using this ability of typecasting it is possible for create ASCII characters by typecasting integer to its character equivalent.

Typecasting is also used in arithmetic operation to get correct result. This is very much needed in case of division when integer gets divided and the remainder is omitted. In order to get correct precision value, one can make use of typecast as shown in example above. Another use of the typecasting is shown in example below

For instance:

int a = 5000, b = 7000 ;
long int c = a * b ;

Here two integers are multiplied and the result is truncated and stored in variable c of type long int. But this would not fetch correct result for all. To get a more desired output the code is written as

long int c = (long int) a * b;

Though typecast has so many uses one must take care about its usage since using typecast in wrong places may cause loss of data like for instance truncating a float when typecasting to an int.

Editorial Team at Geekinterview is a team of HR and Career Advice members led by Chandra Vennapoosa.

Editorial Team – who has written posts on Online Learning.

Pin It

Leave a Reply