GeekInterview.com
  I am new, Sign me up!
 
Home C
 

typecasting in C

 
Category: C
Comments (1)


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


main()
{
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:


main()
{
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.



Read Next: Operator, Operand and Expression in C



 
Related Topics


 

Comments


manoj said:

  ya.. it is very easy to understand the concept. it was crisp.
September 12, 2008, 8:12 am

rupesh said:

  Can we type cast any LONG value to CHAR.
And send it to lcd_puts(char* str); as a string
???
December 8, 2008, 9:52 am

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 
About Us -  Privacy Policy -  Terms and Conditions -  Contact  

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape