Brief Full Advanced Search Search Tips
|  |  | To access the contents, click the chapter and section titles. C++ in Plain English (Publisher: IDG Books Worldwide, Inc.) Author(s): Brian Overland ISBN: 1558284729 Publication Date: 04/01/96 Search this book:
Previous | Table of Contents | Next
One of the important differences between C++ and certain other languages is that in C++, main is a function just like any other. It has only two unique features: it is the program entry point, and it doesn’t need a prototype. Variables declared in main are local variables. For example, in the following definition of main, the variables a, b, c, and h are all local to main.
    void main () {
       double a, b, c, h;

       a = b = c = 1;
       print_vars(a, b, c);
       h = Pythagorus(a, b);
       print_vars(a, b, c);
    }
What’s notable here is that the Pythagorus function operates on its own local variable c without affecting the value of c in main. #### Global Variables It’s usually preferable to make a variable local, but sometimes you need scope that extends beyond a single function. Global variables have scope and lifetime that extend to the entire source file. One purpose of global variables is to enable communication between functions by letting them share information. To make a variable global, simply define it outside all function definitions. The example program in Figure 2.7 uses three global variables. All the functions in the program share common access to the variables a, b, and c, and any function can set or read their values. Figure 2.7 Global variable example.
| Global variables are visible from the point where they are declared to the end of the source file. Generally, you should declare them near the beginning of the program unless you want them to be visible only to some functions.
#### Static Variables A static variable combines the visibility of a local variable with the extended lifetime of a global variable. This capability is useful when you want to make a variable private to a single function (as with a local variable) but make it retain its value between function calls. For example:
    void print_vars (int i1, int i2, int i3) {
       static int count = 0;

       printf(“The value of param1 is %d.\n”, i1);
       printf(“The value of param2 is %d.\n”, i2);
       printf(“The value of param3 is %d.\n”, I3);

       count = count + 1;
       printf(“I’ve been called %d time(s).\n\n”,
       count);
    }
The variable count is initialized to zero just once. After each call to print_vars, the value increases by 1. At the same time, count is private to this function and is not affected by what happens to count variables in other functions. #### External Variables As a program grows in size, it’s common to divide the code into multiple modules, compile them, and then link them. A module corresponds to one C++ source file. Each function is automatically visible to all other modules in the project unless you declare it static (by placing the static keyword at the beginning of the prototype and the function-definition heading); in that case, the function is visible only within the module. Variables are visible only in the module where they’re declared unless you make them external. To make a variable external, first define it as a global variable in exactly one module. (By defining a variable, I mean to use a normal declaration that creates the variable.)
    int global_count;
All other modules that use this same variable need to include an extern declaration:
    extern int global_count;
This declaration (which is not a definition) says to the compiler, “Recognize global_count as an external variable. It may be defined here or in another module.” Another way to use external variables is to throw all the extern declarations into a header file, which is then included in every source file. For example:
    // ——————————————————-
    // MYPROG.H - Extern declarations and function
    // prototypes for myprog.

    extern int global_count;
    extern int current_checkno;
    extern double accumulator;
    ...
Each of these variables must be defined in one—and only one—source-code module. For example, module A might define the first two variables:
    // ——————————————————-
    // A.CPP

    #include “myprog.h”

    int global_count;
    int current_checkno;
    ...
Module B might define the third external variable:
    // ——————————————————-
    // B. CPP

    #include “myprog.h”

    double current_accumulator;
    ...
No matter where they are defined, these three variables are shared by all functions in the program because of the extern declarations in the header file. ### Fun with Control Structures Control structures allow you to express decisions and loops in a readable way. This arrangement frees you from having to use the spaghetti-code style of programming seen in old versions of Basic and in most assembly language. This section introduces the two most frequently used control structures: if and while. C++ also supports the do, for, and switch control structures, which are discussed as topics in Part III. #### The if Statement Here’s the syntax for the C++ if statement:
    if (expression)
        statement
    [ else
        statement ]
Here, the brackets indicate that the else clause is optional. An if statement can appear without else, as in the following example.
    if (age < 21 )
       printf(What you think you’re doing?\n);
An if statement can also include an else clause, as in the next example.
    if (age < 21)
       printf(What you think you’re doing?\n);
    else
       printf(Eat, drink, and be computer literate.\n);
Technically speaking, there is no C++ “elseif” keyword like the one is in Visual Basic. However, the statement following else can itself be another if statement. This is a common example of nesting one control structure inside another:
    if (age < 21 )
       printf(“What you think you’re doing?\n”);
    else
       if (age == 21)
         printf(“Okay, just one drink.\n”);
       else
         printf(“Eat, drink, and be computer literate.\n”);
Because C++ doesn’t care about spacing, we can rewrite it this way:
    if (age < 21 )
       printf(“What you think you’re doing?\n”);
    else if (age == 21)
       printf(“Okay, just one drink.\n”);
    else
       printf(“Eat, drink, and be computer literate.\n”);
Control structures, such as if, are frequently used with compound statements. A compound statement consists of any number of statements placed between braces ({}). The interesting twist is that a compound statement can be used anywhere a single statement can be used. This gives us a nice, structured way to execute multiple statements in response to a condition:
    if (age < 21) {
       printf(“Hey! What do you think you’re
       doing ... ?\n”);
       printf(“Serve minors? Just what kind of place ”);
       printf(“do you\nthink we run?\n”);
    }
    else if (age == 21)
       printf(“Okay, just one drink.\n”);
    else {
       printf(“Eat, drink, and be computer literate.\n”);
       printf(“But we suggest that you be careful \n”);
       printf(“driving home on the information super-\n”);
       printf(“highway tonight...);
    }
| The test for equality used in conditions is the double equal sign (==). Confusing this with assignment (=) is a major cause of errors.
Previous | Table of Contents | Next
[an error occurred while processing this directive]

| Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.