next up previous
Next: Example - The earthquake-proof Up: Finite difference methods for Previous: The routine runge

Use of global variables in C programs

In the following exercises you will have a main program that calls runge which in turn calls der to calculate derivatives. der will need access to variables set in the main program (mass of the oscillator,elastic constant etc). Passing several variables down through several levels of function calls can become tedious. This tedium can sometimes be avoided by the use of global variables. Under the scope rules of C, variables declared outside a function (including main) are global and may be referred to in another function using the extern keyword.

Example of global variables

#include <plplot.h>       /* Start of main program */

	float a,b,c,m,w; /* Global variables */
	void der(float,float [],float []); /* Describe structure of der */
	void runge(int,float,float,float [],void (float,float [],float []));

main()
{	main() will call runge which in turn will call der ....

}
------------------------------------------------------

In writing der :

#include <math.h>
	
	extern float a,b,c,m,w;
	void der(float t,float y[],float dydt[])
{
	now calculate the derivatives with access to the values of
 a,b,c,m,w . We avoided having to pass all these down from main via runge.
 We don't have to modify runge every time we write a new 'der' for a different
 set of differential equations.
}



Keith Jones
Sun Jan 23 14:17:38 EST 2000