Govt Exam Preparation Guidance & Previous Year Papers, Study Materials & Job Updates - For Engineers
Enter Your Email Address To Get Study Materials & Job Updates In Your Mail :

                             (Please activate subscription from your mail Inbox)  FeedBurner

Submit Your Resume/ CV Directly To Companies HR Trough Us - Free

Home » » What is Coercion or Type-Casting explain with example

What is Coercion or Type-Casting explain with example

What is Coercion or Type-Casting explain with example

Coercion or Type-Casting
C is one of the few languages to allow coercion, that is forcing one variable of one type to be another type. C allows this using the cast operator (). So:

  int integernumber;
         float floatnumber=9.87;

                 integernumber=(int)floatnumber;

assigns 9 (the fractional part is thrown away) to integernumber.

And:

  int integernumber=10;
         float floatnumber;

                 floatnumber=(float)integernumber;

assigns 10.0 to floatnumber.
Coercion can be used with any of the simple data types including char, so:

          int integernumber;
         char letter='A';

                 integernumber=(int)letter;
assigns 65 (the ASCII code for `A') to integernumber.
Some typecasting is done automatically -- this is mainly with integer compatibility.
A good rule to follow is: If in doubt cast.
Another use is the make sure division behaves as requested: If we have two integers internumber and anotherint and we want the answer to be a float then :

e.g.
 floatnumber =
         (float) internumber / (float) anotherint;

ensures floating point division.
Share this article :

0 comments:

Speak up your mind

Tell us what you're thinking... !

Search - Get Answer Of Your Question

Loading...
 
Support : Campusnikalo | Job Search Site | Graduates Freshers Jobs
Copyright © 2011. Campus Nikalo - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger