C++
  Home arrow C++ arrow Page 7 - First Steps in (C) Programming, continued
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
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, continued
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 11
    2005-11-23

    Table of Contents:
  • First Steps in (C) Programming, continued
  • Variables and Memory
  • Integer Constants
  • Floating-Point Variables
  • More on Format Specifiers
  • More Complex Expressions
  • Defining Constants
  • Try It Out: The Right Types of Variables

  • 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
     
     
    ADVERTISEMENT


    First Steps in (C) Programming, continued - Defining Constants


    (Page 7 of 8 )

    Although you definedPias a variable in the previous example, it’s really a constant value that you don’t want to change. The value of π is always a fixed number. The only question is how many digits precision you use in its specification. It would be nice to make sure its value stayed fixed in a program so it couldn’t be changed by mistake.

    You actually have a couple of ways in which you can approach this. The first is to definePias a symbol that’s to be replaced in the program by its value during compilation. In this case,Piisn’t a variable at all, but more a sort of alias for the value it represents. Let’s try that out.

    ..........................................................................................

    Try It Out: Defining a Constant

    Let’s look at specifying PI as an alias for its value:

    /* Program 2.9 More round tables */ #include <stdio.h>
    #define PI  3.14159f    /* Definition of the symbol PI */
    void main()
    {
      float radius = 0.0f;
      float diameter = 0.0f;
      float circumference = 0.0f;
      float area = 0.0f;
     
    printf("Input the diameter of a table:"); 
      scanf("%f", &diameter);
      radius = diameter/2.0f;
      circumference = 2.0f*PI*radius;
      area = PI*radius*radius;
      printf("\nThe circumference is %.2f", circumference);
      printf("\nThe area is %.2f", area);
    }

    This produces exactly the same output as the previous example.

    HOW IT WORKS

    After the comment and the#includedirective for the header file, you have a preprocessing directive:

    #definePI 3.14159f    /* Definition of the symbol PI */

    You’ve now definedPIas a symbol that is to be replaced in the code by3.14159f. You usePI rather thanPi, as it’s a common convention in C to write identifiers that appear in a#definestatement in capital letters. Wherever you referencePIwithin an expression in the program, the compiler will substitute the value you’ve specified for it in the#definedirective. All the substitutions will be made before compiling the program. When the program is ready to be compiled, it will no longer contain references toPI, as all occurrences will have been replaced by the sequence of characters that you’ve specified in the#definedirective. This all happens internally while your program is processed by the compiler. Your source program will not be changed: it will still contain the symbolPI.

    ..........................................................................................

    The second possibility is to definePias a variable, but to tell the compiler that its value is fixed and must not be changed. You can fix the value of any variable by prefixing the type name with the keywordconstwhen you declare the variable, for example:

    const float Pi = 3.14159f;    /* Defines the value of Pi as fixed */

    Adding the keywordconstin the declaration forPi will cause the compiler to check that the code doesn’t attempt to change its value. Any code that does so will be flagged as an error and the compilation will fail. Let’s see a working example of this.

    ..........................................................................................

    Try It Out: Defining a Variable with a Fixed Value

    You’ll try using a constant in a variation of the previous example but shorten the code a little:

    /* Program 2.10 Round tables again but shorter */
    #include <stdio.h>
    void main()
    {
      float diameter = 0.0f;  /* The diameter of a table   */
      float radius = 0.0f;    /* The radius of a table     */
      const float Pi = 3.14159f; /* Defines the value of Pi as fixed */
      printf("Input the diameter of the table:");
      scanf("%f", &diameter);
      float radius = diameter/2.0f;
      printf("\nThe circumference is %.2f", 2.0f*Pi*radius);
      printf("\nThe area is %.2f", Pi*radius*radius);
    }

    HOW IT WORKS

    Following the declaration for the variableradius, you have this statement:

    const float Pi = 3.14159f;  /* Defines the value of Pi as fixed */

    This declares the variablePiand defines a value for it;Piis still a variable here, but the initial value you’ve given it can’t be changed. Theconstmodifier achieves this effect. It can be applied to any statement declaring a variable of any type to fix the value of that variable. Of course, the value must appear in the declaration in the same way as shown here: following an=sign after the variable name. The compiler will check your code for attempts to change variables that you’ve declared asconst, and if it discovers that you’ve attempted to change aconstvariable it will complain. There are ways to trick the compiler to changeconstvariables, but this defeats the whole point of usingconstin the first place.

    The next two statements produce the output from the program:

    printf("\nThe circumference is %.2f", 2.0f*Pi*radius);
    printf("\nThe area is %.2f", Pi*radius*radius);

    In this example, you’ve done away with the variables storing the circumference and area of the circle. The expressions for these now appear as arguments in the printf() statements where they’re evaluated, and their values are passed directly to the function.

    As you’ve seen before, the value that you pass to a function can be the result of evaluating an expression rather than the value of a particular variable. The     compiler will create a temporary variable to hold the value and that will be passed to the function. The temporary variable is subsequently discarded. This is fine, as long as you don’t want to use these values elsewhere.

    ..........................................................................................

    Choosing the Correct Type for the Job

    You have to be careful when doing calculations as to the type of variable that you’re using. If you use the wrong type, then you may find that errors creep into your programs that can be hard to detect. This is best shown with an example.

    ..........................................................................................

    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 today. Buy this book now.

    C++ ARTICLES

    - 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++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT