C Scope

Scope describes where in your program a variable can be seen and used. In C, a variable is only alive within the region where it was declared. Understanding scope helps you avoid confusing errors like 'undeclared variable' and keeps different parts of your program from stepping on each other.

Local Scope

A variable declared inside a function is called a local variable. It exists only while that function runs and can only be used inside that function. Other functions cannot see it, even if they use the same name. This keeps each function nicely self-contained.

A local variable

#include <stdio.h>

void showNumber() {
  int x = 42;
  printf("Inside the function x is %d\n", x);
}

int main() {
  showNumber();
  return 0;
}
Note: If you tried to print x from inside main() in the example above, the program would not compile. The variable x only exists inside showNumber(), so main() has no idea it exists.

Global Scope

A variable declared outside of all functions, usually near the top of the file, is called a global variable. Every function in the file can read and change it. Globals can be handy, but use them carefully because any function can modify them, which can make bugs harder to track down.

A global variable shared by functions

#include <stdio.h>

int counter = 0;

void increase() {
  counter++;
}

int main() {
  increase();
  increase();
  printf("Counter is now %d\n", counter);
  return 0;
}

Block Scope

Scope can be even narrower than a whole function. A variable declared inside a block, such as inside an if statement or a loop, only lives until that block's closing brace. This is called block scope.

A variable that lives only inside the loop

#include <stdio.h>

int main() {
  for (int i = 1; i <= 3; i++) {
    int doubled = i * 2;
    printf("%d doubled is %d\n", i, doubled);
  }
  return 0;
}
  • Local variables are safest because they can not be changed from elsewhere
  • Global variables are visible everywhere in the file
  • Block variables disappear as soon as the block ends
  • When names clash, the innermost (most local) variable wins

Types of scope

ScopeWhere declaredWho can use it
LocalInside a functionOnly that function
GlobalOutside all functionsEvery function in the file
BlockInside { } of a loop or ifOnly inside that block