next up previous
Next: Function Arguments as References Up: Getting More Out of Previous: Function Arguments as Pointers

Variable Scope

The variable x in the subprogram is actually distinct from the variable x in the main program, although we used the same name for them. We use the term ``scope'' to specify the portion of code in which a given declared identifier is known. Here are the basic scoping rules: Local declarations override previous global declarations. However, such programming practice is an invitation to confusion, so it is discouraged. If you do this with a variable, you might get a warning message from the compiler, complaining that the second, overriding declaration ``shadows a parameter''.

So according to the scoping rules, the name of the subprogram f_and_df is defined in the main program, only if we put its declaration or definition before the main program. Putting the definition (the whole code for the subprogram) ahead of the int main statement is sufficient. But if you prefer, you can put the code for the subprogram later in the file after the closing brace for the main program, or even in a separate file, as long as you insert a function declaration statement before the int main statement. Such a statement is called a ``forward declaration''. Here is how it is done:

// Forward declaration of the subprogram
void f_and_df(double x, double *fp, double *dfdxp);

int main(){
     double f, dfdx;
     ...

     // The calling statement:
     f_and_df(x, &f, &dfdx);  // Arguments 2 and 3 are pointers to doubles
     ...
}

// The code that follows could even be in a different file if you like:
void f_and_df(double x, double *fp, double *dfdxp){
   *fp = 4*x - cos(x);         // the * dereferences the pointer
   *dfdxp = 4 + sin(x);
}

The forward subprogram declaration at the top is also called a prototype declaration. A recommended rule for constructing the prototype declaration is simply to copy the first statement of the function definition and end it with a semicolon.
next up previous
Next: Function Arguments as References Up: Getting More Out of Previous: Function Arguments as Pointers
Carleton DeTar 2009-09-23