Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
"extern" keyword in C
The extern keyword in C is used to declare variables and functions that are defined elsewhere, either in the same file or in other source files. It extends the visibility of variables and functions across multiple files, making them globally accessible.
Syntax
extern data_type variable_name; extern data_type function_name(parameters);
Key Properties
Scope − Global throughout the program, not bound by any function.
Default value − Global variables are initialized to zero by default.
Lifetime − Exists until the end of program execution.
Important Points
- External variables can be declared multiple times but defined only once.
- The
externkeyword extends visibility of variables across files. - Functions are
externby default − explicit declaration is optional. - Variables with
externare only declared, not defined (unless initialized). - Initialization of an
externvariable counts as its definition.
Example: Basic extern Usage
#include <stdio.h>
extern int x = 32; /* Definition with initialization */
int b = 8; /* Global variable definition */
int main() {
auto int a = 28;
extern int b; /* Declaration referring to global b */
printf("The value of auto variable: %d
", a);
printf("The value of extern variables x and b: %d, %d
", x, b);
x = 15; /* Modifying extern variable */
printf("The value of modified extern variable x: %d
", x);
return 0;
}
The value of auto variable: 28 The value of extern variables x and b: 32, 8 The value of modified extern variable x: 15
Example: Declaration vs Definition
#include <stdio.h>
int global_var = 100; /* Definition */
extern int global_var; /* Declaration only */
int main() {
printf("Global variable value: %d
", global_var);
extern int global_var; /* Another declaration */
global_var = 200; /* Modification */
printf("Modified global variable: %d
", global_var);
return 0;
}
Global variable value: 100 Modified global variable: 200
Conclusion
The extern keyword is essential for creating global variables and sharing data across multiple source files in C. It allows declaration without definition, enabling modular programming and code organization across files.
Advertisements
