Saturday, May 30, 2009

Know Local and Global Variables

I remember during summer classes that one of my students asked me about making her main menu for a number system conversion. I answered her to make use of functions to break down the conversions into binary, octal, hexadecimal and decimal and vice versa. Further, I added that she can use local and global variables to pass values among functions. She replied," What are local and global variables, maam?"

It hit me that I missed to cover these variables in details. Programming languages like C or C++ do differentiate global and local variables.

If variables are declared before the main() function, then these variables are declared global. These variables can then be accessed anywhere inside and outside the main function.

However, the opposite of this declaration is the declaration of variables within the main function. These variables are local, thus, they are only valid and known within the main body.

Click Show/Hide link for the sample.

[+/-] show/hide

#include stdio.h /*enclose this in <> */
int compute(int birthyear);
int currentyear=2009; /*this is global variable*/
int birthyear; /*this is a local variable*/
printf("\nEnter your birthyear : ");

printf("Your age is %d ",compute(byear));

int compute(int birthyear) /* these are your formal parameters */
return currentyear-birthyear; /* 2009 is passed to currentyear with the encoded value for birthyear*/