C Language | Functions | Variable Scope

The scope and lifetime of a variable depend on where it is declared.

Automatic Variables

A variable declared inside a block is an automatic variable, also called a local variable. It is created when execution enters the block and is discarded when execution leaves it. The variable is visible only inside that block.

void Function(void) {
  int iValue;
}

int main(void) {
  int iValue;
}

These two variables have the same name but do not conflict because their scopes differ. Scope applies to blocks, not only to functions.

#include <stdio.h>

int main(void) {
  {
    int iCount;
    for (iCount = 0; iCount < 10; iCount++)
      printf("1st for : iCount = %d\n", iCount);
  }
  {
    int iCount;
    for (iCount = 0; iCount < 10; iCount++)
      printf("2nd for : iCount = %d\n", iCount);
  }
  return 0;
}

External Variables

A variable declared outside a function is an external variable, also called a global variable. Its lifetime lasts until the program terminates, and functions can share it.

#include <stdio.h>

int iValue = 10;
void Function(void);

int main(void) {
  Function();
  iValue = 100;
  Function();
  return 0;
}

void Function(void) {
  printf("iValue = %d\n", iValue);
}

Global variables can make large programs difficult to understand because any function may change them. Prefer parameters and return values unless shared state is necessary.

When a local and global identifier have the same name, the nearest local declaration takes precedence.