Home arrow C++ arrow Page 7 - First Steps in (C) Programming, continued
C++

First Steps in (C) Programming, continued


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 second 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 / 22
November 23, 2005
TABLE OF CONTENTS:
  1. · First Steps in (C) Programming, continued
  2. · Variables and Memory
  3. · Integer Constants
  4. · Floating-Point Variables
  5. · More on Format Specifiers
  6. · More Complex Expressions
  7. · Defining Constants
  8. · Try It Out: The Right Types of Variables

print this article
SEARCH DEVARTICLES

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.

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


blog comments powered by Disqus
C++ ARTICLES

- 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 
Support 

Developer Shed Affiliates

 




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