Lesson 8.6. Global variables

Definition

A global variable is a variable declared outside all functions. Its scope extends from its declaration to the end of the program, its memory allocation too. A global variable permanently allocates the memory space intended for it.

As far as possible, the use of global variables should be avoided.

Prefer local variables and parameter passed to functions instead of global variables.

If within a function a variable coexists with a global variable of the same name, it is the local variable that is considered in the function.

Example

Here is an example of a program that uses a global variable:

int i=0; // Global variable i

void fct(void);

int main(void) {
  for ( ;i<5;i++)   // The loop uses i
    fct ();
  return 0;
}

void fct(void) {
  printf ("i= %d\n", i);  // The function also uses i
}

The variable i is a global variable that is readable and writable in the main() and in the fct() function.

Exercise

The following program is provided which contains 4 global variables. Correct the program to remove all global variables by replacing them with local variables and functions arguments.

# include <stdio.h>

// Global variables TO BE DELETED
int a,b,c,sum;

// Function that ask for an integer
void input (void);

int main(void)
{
  // Ask the first integer
  input(); 
  a=c; 

  // Ask the second integer
  input();
  b=c;

  // Display the sum
  sum=a+b;
  printf ("The sum is %d\n",sum);
  return 0 ;
}

// Function that ask for an integer
void input (void)
{
  printf ("Enter an integer: ");
  scanf ("%d",&c);
}

Quiz

Global variables are...

Check Bravo! Global variable must be avoided. Try again...

The scope of a global variable is ...

Check Bravo! The scope of a global variable starts at its declaration. Try again...

The memory allocated for a global variable ...

Check Bravo! A global variable occupies memory space until the end of the program. Try again...

What does the following program display?

#include <stdio.h>
int var = 7;

int main(void) {
  int var = 12;
  printf ("var = %d",var);
  return 0;
}
Check Bravo! There are two variables named var: a local and a global. Local variables overwrite global variables. Try again...

See also


Last update : 11/21/2022