C++
  Home arrow C++ arrow First Steps in (C) Programming, conclusion
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
Moblin 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

First Steps in (C) Programming, conclusion
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 53
    2005-12-01

    Table of Contents:
  • First Steps in (C) Programming, conclusion
  • More Numeric Data Types
  • Try It Out: Character Building
  • Unsigned Integers: Using Positive Integers
  • Try It Out: Finding the Limits
  • Mathematical Functions
  • Designing a Program
  • The Solution
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Iron Speed
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    First Steps in (C) Programming, conclusion


    (Page 1 of 9 )

    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).

    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.

    More C++ Articles
    More By Apress Publishing


       · This article is an excerpt from the book "Beginning C", published by Apress. We hope...
     

    Buy this book now. This article is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530). Check it out at your favorite bookstore. Buy this book now.

    C++ ARTICLES

    - Large Numbers
    - Dijkstra`s Shunting Algorithm with STL and C...
    - Brief Introduction to the STL Containers
    - The Standard Template Library
    - Templates in C++
    - C++ Programmer Alerts
    - C++ Programming Tips
    - First Steps in (C) Programming, conclusion
    - First Steps in (C) Programming, continued
    - First Steps in (C) Programming, introduction
    - C++ Preprocessor: Always Assert Your Code Is...
    - C++ Preprocessor: The Code in the Middle
    - Programming in C
    - Temporary Variables: Runtime rvalue Detection
    - Temporary Variables: Chasing Temporaries Away







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway