C examples for Language Basics:Variable
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.
#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.
#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.
#include <stdio.h> int main(void) { int localVar = 0; /* initialized to 0 */ }