Variable Scope - C Language Basics

C examples for Language Basics:Variable

Introduction

The scope of a variable is the region of code where the variable can be accessed.

Variables in C can be global and local.

A global variable is declared outside of any code blocks and is accessible from anywhere.

A local variable is declared inside of a function and will only be accessible within that function.

A global variable will remain allocated for the duration of the program.

A local variable will be destroyed when its function has finished executing.

Demo Code

#include <stdio.h>
int globalVar; /* global variable */

int main(void) {
  int localVar; /* local variable */
}

Global variables are automatically initialized to zero by the compiler.

Local variables are not initialized at all.

Demo Code

#include <stdio.h>
int globalVar; /* initialized to 0 */

int main(void) {
  int localVar; /* uninitialized */
}

It is a good idea to give your local variables an initial value when they are declared.

Demo Code

#include <stdio.h>
int main(void) {
  int localVar = 0; /* initialized to 0 */
}

Related Tutorials