Home arrow C++ arrow First Steps in (C) Programming, conclusion

First Steps in (C) Programming, conclusion

If you're a beginning programmer and want to get more deeply into programming with variables, you've come to the right place. This article, the third of three parts, is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 63
December 01, 2005
  1. · First Steps in (C) Programming, conclusion
  2. · More Numeric Data Types
  3. · Try It Out: Character Building
  4. · Unsigned Integers: Using Positive Integers
  5. · Try It Out: Finding the Limits
  6. · Mathematical Functions
  7. · Designing a Program
  8. · The Solution
  9. · Summary

print this article

First Steps in (C) Programming, conclusion
(Page 1 of 9 )

Type Casting in Arithmetic Expressions

Letís look at the original expression to calculate the quarterly revenue again and see how you can control what goes on so that you end up with the correct result:

RevQuarter = QuarterSold/150*Revenue_Per_150;

You know that if the result is to be correct, this statement has to be amended so that the expression is calculated in floating-point form. If you cast the value ofQuarter-Soldto typefloat, then the expression will be evaluated as floating-point and your problem will be solved. To convert the value of a variable to another type, you place the type that you want to cast the value to in parentheses in front of the variable. The statement to calculate the result correctly will thus be

RevQuarter = (float)QuarterSold/150.0f*Revenue_Per_150;

This is exactly what you require. Youíre using the right types of variables in the right places. Youíre also ensuring you donít use integer arithmetic when you want to keep the fractional part of the result of a division.

Automatic Casting

Look at the output from the second version of the program again:

Sales revenue this quarter is: $1930.50

Even without the explicit cast statement in the expression, the result was in floating-point form, even though it was still wrong. This is because the compiler automatically casts one or other of the operands when itís dealing with an operation that involves values of different types. Your computer can perform only binary arithmetic operations (add, subtract, multiply, divide, and remainder) when both operands are of the same type. When the operands that are involved in an operation are of different types, the compiler arranges for the value that is of a type with a more limited range to be converted to the type of the other variable. So, referring back to the expression to calculate revenue:

QuarterSold / 150 * Revenue_Per_150

This was evaluated as 64400 (int)/150 (int), which equals 429 (int). Then 429 (intconverted tofloat) is multiplied by 4.5 (float), giving 1930.5 (float).

An automatic conversion applies when a binary operator applies operands of different types. With the first operation, the numbers are both of typeint, so the result is of typeint. With the second operation, the first value is typeintand the second value is typefloat. Typeintis more limited in its range than typefloat, so the value of typeintis automatically cast to typefloat. Whenever there is a mixture of types in an arithmetic expression, C will use a set of specific rules to decide how the expression will be evaluated. Letís have a look at some of these conversion rules now.

Conversion Rules in Casting

As Iíve said, for each operation in an expression that involves operands of different types, your compiler will promote the operand with the type that has the more restricted range of values to be the same type as the other operand. The order of types in this context from highest to lowest islong double, thendouble, thenfloat, followed bylong, thenint, thenshort, and finally the lowest,char. You havenít seen typecharyet, but youíll be looking at it in a moment.

Letís see how these conversion rules apply in practice. Suppose you declare three variables:Aas typedouble,Bas typefloat, andC as typelong. You can see how the expressionA + B - Cwill be evaluated.

The operationA + B will be carried out first. BecauseAis typedoubleandBis typelong,Bwill be converted to typedoubleand the result will therefore be typedouble. To subtractCfrom this result,Cis first converted todouble and you end up with the final result as typedouble.

Casts in Assignment Statements

You can also cause an implicit cast to be applied by assigning the value of one type to a variable of a different type. This can cause values to be truncated so information is lost.

For instance, if you assign afloatordoublevalue to a variable of typeintorlong, the fractional part of thefloatordoublewill be lost, and just the integer part will be stored. The following code fragment illustrates this situation:

int number = 0;
float value = 2.5f;
number = value;

The value stored innumberwill be 2. Because youíve assigned the value ofdecimal(2.5) to the variable,number, which is of typeint, the fractional part,.5, will be lost and only the2will be stored. Notice how Iíve used a specifier fat the end of2.5f.

Note that an assignment statement that may lose information because an automatic cast has to be applied will usually result in a warning from the compiler. However, the code will still compile, so thereís a risk that your program may be doing things that will result in incorrect results. Generally, itís better to put explicit casts in your code wherever conversions that may result in information being lost are necessary.

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials