Variable Scope

This is one of the toughest concepts for beginning (and some advanced) computer science students to understand.

global vs. local

A local variable is declared within a function. It exists only within that function. When the function ends, the variable ceases to exist. So, the variable is 'hidden' from everything outside of the function. It seems like a simple concept, but it's easy to get confused. Here's an example that's intended to confuse you. (If it doesn't, great!)

#include <stdio.h>

int confusion (int x, int y)
{
   x = 2*x + y;
   return x;
}

void main()
{
   int x = 2;
   int y = 5;
   y = confusion(y,x);
   x = confusion(4,x);
   printf("x is %d and y is %d\n", x, y);
}

Question: What is printed? [answer]

A global variable is declared outside of (usually before) all (including main) functions in the program. Any function can access the variable and change its value. Although it is tempting to declare many variables easier (to make your functions simpler to write), it is generally considered poor programming practice to declare variables as global unnecessarily. Don't worry too much about this now - your programming style will develop over time.

What's wrong with the following code fragment? [answer]

#include <stdio.h>

int my_global;

int function1()
{
   my_global = 6;
   my_local = 2;
   return 1;
}

void function2()
{
   int my_local = 10;
   my_global = my_local;
}