extern and Global
Sharing across files.
Global Variables
A variable declared outside any function has file scope and lives for the whole program. It is a global.
#include <stdio.h>
int counter = 0;
void bump(void) {
counter++;
}
int main(void) {
bump();
bump();
printf("counter = %d\n", counter);
return 0;
}Globals Are Shared
Every function in the file can read and write a global. This makes them convenient but easy to misuse.
#include <stdio.h>
int score = 100;
void penalty(void) { score -= 25; }
void bonus(void) { score += 10; }
int main(void) {
penalty();
bonus();
printf("score = %d\n", score);
return 0;
}All lessons in this course
- auto and Local Scope
- static Variables
- extern and Global
- register and const