Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   C-Style TypeCasts (http://www.go4expert.com/articles/c-style-typecasts-t27437/)

Trinity 25Dec2011 16:27

C-Style TypeCasts
 
Type casting is an explicit type conversion requested by the programmer to achieve its objective in the program. During any kind of computations involving various data variables of different data types, leads to the need of typecasting.

Syntax used:
Code:

(Data-type-2)<variable/expression of data type 1>
There are certain implicit type conversions as well which are called the promotions, widening, etc. However we'll be discussing about explicit type castings only here.

An example - explaining the problem



Lets take a simple example,

Here is a code snippet from a C program which calculates the percentage, given the marks obtained and the max total marks.
Code:

  int marks = 0;
  int total = 100;
  float percentage = 0.0;

  printf("Enter the marks obtained \n");
  scanf("%d", &marks);
  printf("Out of : \n");
  scanf("%d", &total);

  percentage = (marks/total)*100;
  printf("Percentage is %f\n", percentage)

Note that, the code assumes the 'marks' and 'total' would be integers, and hence are stored in datatype 'int'. Whereas, since percentage is calculated using division operation, so but obvious, it would be in floating points, hence the variable 'percentage' is stored in datatype 'float'.

Now lets the run the above code
Code:

Enter the marks obtained
33
Out of :
120
Percentage is 0.00000

Ouch! zero? Any school kid would also be able to this simple division, and give the correct answer. Then what makes it give the result as 0.0 here?

The solution - Typecasting



Yes, you got it right, its the datatype which had played the vital role in this simple computation. Here is the victimized statement of the program:
Code:

  percentage = (marks/total)*100;
The way the R-value of the expression is computed at the machine level instaruction level, is storing every intermrdiate value in a temporary variable. Now, the question comes, what is the data type of this temporary variable. The larger of the two operand data type is chosen as the data type of the temporary variable which stores the intermediate value. With this detail, following operation at the machine instruction level would be performed;
Code:

marks/total
The operands are
  1. marks - datatype is int (4 bytes for gcc)
  2. total - datatype is int (4 bytes for gcc)
Hence, larger of the two is also 'int' as both the operands are int.
By value, it becomes the absolute value i.e.
Code:

|33/120| = 0
Next operation would be the multiplication by 100 which is again an int, hence the resultant value becomes
Code:

0 * 100 = 0
Since, this value is stored in a float variable, therefore the final value is printed as
Code:

0.000000
Now, we understood this unexpected output. What to do to make it right?

If we need to compute the correct float value, we have following probable solutions:
  • Store either the marks or total or both in float data type. But this might not be space-efficient as we already know neither the marks nor the total would ever be containing a float value.
  • Type-Casting - type-cast one of the operand as float during the computation.
    as in,
    Code:

    percentage = ((float) marks/total)*100;
    Now, marks is interpretted as a float, and hence the temporary variable would also be a float to be used to store the intermediate value, with the division happening as floating point division.
    Again, for the second operation i.e. the multiplication with 100, intermediate value is stored in float which is finally stored in the float variable 'percentage'.

    Re-compiling and running, we get the correct answer this time
    Code:

    Enter the marks obtained
    33
    Out of :
    120
    Percentage is 27.500000

    It is a pretty efficient solution and hope explains why we need to do typecasting during programming
Now, the next question arises is how exactly this type casting happens. The way they work could differ on how they are being used. It could just mean re-interpretting the same bits to a different datatype or could be creating a new temporary variable and returning the new type casted value.

Caveat



Be very careful while using C style type casting as it could lead to unpredictable results without indicating any errors to the programmer. It can even allow you to convert an adress of a memory (i.e. a pointer) to an int, without any warnings or errors. This explains, the extent to which the onus of type safety, is on the programmer while using c-style type casting.


All times are GMT +5.5. The time now is 09:10.