When to use extern in C/C++


External variables are also known as global variables. These variables are defined outside the function and are available globally throughout the function execution. The “extern” keyword is used to declare and define the external variables.

The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.

The following is the syntax of extern.

extern datatype variable_name; // variable declaration using extern
extern datatype func_name(); // function declaration using extern

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

func_name − The name of function.

The following is an example of extern:

Example

 Live Demo

#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
   extern int b;
   printf("The value of extern variables x and b : %d,%d\n",x,b);
   x = 15;
   printf("The value of modified extern variable x : %d\n",x);
   return 0;
}

Output

The value of extern variables x and b : 32,8
The value of modified extern variable x : 15

In the above program, two variables x and b are declared as global variables.

extern int x = 32;
int b = 8;

In the main() function, variable is referred as extern and values are printed.

extern int b;
printf("The value of extern variables x and b : %d,%d\n",x,b);
x = 15;
printf("The value of modified extern variable x : %d\n",x);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements