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
Here, the string is always printed no matter what value was in n previously, because n = 5 puts 5 into n and then returns 5. This is almost certainly not what was wanted. C++ does not assume that you wanted to test for equality here. After all, there are situations (though infrequent) when you might want to evaluate an assignment inside a conditional. To resolve this ambiguity, C and C++ provide a separate operator to test for equality (==). This operator performs a comparison and evaluates to true (1) or false (0) just as you would expect.
    if (n == 5)                      // Test n against 5.
       printf(“n is equal to 5.\n”); // Print if n eq. 5.
In the history of C and C++, many thousands of programmers have bashed their heads against their desks, trying to find an elusive bug that was caused by using assignment (=), instead of test-for-equality (==), in a conditional. This is by far one of the most common mistakes you’ll make when you are first learning C or C++. Experienced C/C++ programmers usually learn (the hard way) to avoid it. In general, assignment (=) inside a conditional indicates an error, although there are times when it is exactly what you want. Most languages other than C and C++ simply wouldn’t let you do this. (Here’s an axiom for you: with greater freedom comes the mobility to step on your own foot.) ### Adding Functions to Your Program In any computer language, elements such as subroutines, procedures, functions, and GOSUB routines all have the same general purpose: to temporarily transfer control to another part of the program and then return to the same location. In C++, there is just one kind of subroutine: the function. Unless declared void, function calls evaluate to a value upon execution (that is, they return a value). Even when a function does return a value, the caller of the function is free to use that value or ignore it. The practical implication of these features is this: in C++, one type of construct—the function—fulfills the role of functions and procedures in other languages. This fact helps to keep C++ syntax leaner and more streamlined. There is no need for a separate keyword like the Function keyword found in Visual Basic. You’ve almost certainly encountered functions and procedures. A function takes zero or more arguments—depending on how it’s declared—and evaluates to a single value that can be reused in a larger expression. Figure 2.3 illustrates how a call to the Pythagorus function might work. Figure 2.3 A function call in action. In Figure 2.3, the expression Pythagorus(3.0, 4.0) results in a call to the Pythagorus function, passing the values 3.0 and 4.0 to the two parameters. The function uses the return statement to transfer control back to the caller and return the value 5.0. #### General Syntax for Functions When functions are taken into account, the general syntax for a C++ program follows the pattern shown in Figure 2.4: Figure 2.4 General syntax of a C ++ program. Before you call or define a function, you must declare it; function_prototypes serves this purpose. A function prototype provides type information to the compiler so that it knows what type of arguments to expect. You may feel that the C++ compiler is being fussy, but it needs the type information to help catch errors before they happen at run time. The format of a function prototype looks almost identical to that of the first line (the heading) of a function definition:
    return-type function_name(argument_list);
Note, however, that a function prototype ends with a semicolon (;). Do not—repeat, do not—place a semicolon after the terminating brace (}) of a function. Because prototypes end with semicolons and function definitions do not, it is easier for the compiler to tell them apart.
| Prototypes and headings for a function definition are so similar that you can save effort by doing the following: after entering a prototype, make a copy, remove the semicolon, and then proceed to enter the rest of the function definition.
#### Function Example Function syntax makes much more sense in the context of an example. Figure 2.5 illustrates each part of the function syntax, including prototype, function call, and function definition. Each part of this syntax has an important role: the prototype prepares for the function call (by letting the compiler know what types to check for), the function call executes the function, and the function definition tells the compiler how to execute the function. Figure 2.5 An example program that calls a function. For this example, you must include two header files (STDIO.H and MATH.H), because the program uses both I/O functions (printf and scanf) and a math function (sqrt), which takes the square root of a number. A function with any return type other than void must transfer execution back to the caller at some point by using the return statement. A return statement also specifies the value that the function evaluates to. Figure 2.6 analyzes the syntax of the Pythagorus function definition. The return type is double, indicating that the function evaluates to a double-precision floating-point number. Figure 2.6 Breakdown of function-definition syntax. #### Functions in the void If a function does not need to return a value, declare it with the void return type. Unlike functions with other return types, a void function does not need a return statement. The function can use return to exit early, but it can also let execution terminate naturally at the end of the function definition. See the “return” topic in Part III for more information. The following example calls a void function. Note that the function call is not used in a larger expression but instead terminates right away.
    #include <stdio.h>

    void print_vars(int il, int i2, int i3);

    void main() {
       int a, b, c;

       a = b = c = 1;

       print_vars (a, b, c);
       a = b = c = 2;
       print-vars (a, b, c);
    }
    void print_vars (int i1, int i2, int 13) {
       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\n”, i3);
    }
### Local, Global, and Other Variables One of the most important attributes of a variable is its scope, which determines how long a variable lasts and where it is visible (what part of the program can use it). The two fundamental kinds of scope in C++ are local and global. There are also the special kinds of scope: static and external. These four kinds of scope—local, global, static, and external—are inherited from C. To these, C++ adds class scope, which attaches a variable to an object of a particular class. #### Local Variables A local variable is private to a function definition. Each function can have its own variable named variable X, for example, and can modify this variable without affecting the variable named X in any other function. To declare a local variable, simply place the declaration inside a function definition. For example, the variable c is local in the following Pythagorus function definition. If another function had its own variable named c and if this function called Pythagorus, changes to c inside Pythagorus would not affect the other function.
    #include <math.h>
    ...
    double Pythagorus(double a, double b) {
       double c;

       c = sqrt(a * a + b * b);
       return c;
    }
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.