Utilizor
Contact Us

CC Scope

Variable visibility.

C Scope

In C, variables are only accessible inside the region they are created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

Global Scope

A variable created outside of anybody function, is called a global variable and belongs to the global scope.

Examples

Local Scope

c example

x is only available in myFunction.

#include <stdio.h>

void myFunction() {
  // Local variable that belongs to myFunction
  int x = 5;
  printf("%d", x);
}

int main() {
  myFunction();
  // printf("%d", x); // This would cause an error
  return 0;
}

Global Scope

c example

x is available everywhere.

#include <stdio.h>

int x = 5; // Global variable

void myFunction() {
  printf("%d\n", x);
}

int main() {
  myFunction();
  printf("%d\n", x);
  return 0;
}

Test Your Knowledge

1. Where is a local variable declared?

2. Can a global variable be accessed by any function?