Extern Keyword in C

Level 5272 keystrokes

Defines global_var with external linkage and file_var with static (internal) linkage, and a function that refers to global_var through an extern declaration and adds 10 and 20 to the two variables. It prints global=100, file=200 before the call and global=110, file=220 after.

C code

// A global with external linkage: other source files can use it via extern
1int global_var = 100;
// static at file scope gives internal linkage: visible only in this file
2static int file_var = 200;
3
// Changes both file-level variables
4void modifyGlobals() {
// extern declares without defining; it refers to the global_var defined above
5 extern int global_var;
// 100 + 10 = 110
6 global_var += 10;
// The static variable is usable anywhere in this file: 200 + 20 = 220
7 file_var += 20;
8}
9
// Prints Before: global=100, file=200
10printf("Before: global=%d, file=%d\n", global_var, file_var);
// Updates both variables
11modifyGlobals();
// Prints After: global=110, file=220
12printf("After: global=%d, file=%d\n", global_var, file_var);

Output

Before: global=100, file=200
After: global=110, file=220
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • _× 9
  • ;× 8
  • =× 8
  • ,× 6
  • "× 4
  • (× 4
  • )× 4
  • %× 4
  • :× 2
  • \× 2

More C examples at level 5

← C typing practice