You are on page 1of 2

10/5/2020 When to use extern in C/C++

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.

https://www.tutorialspoint.com/when-to-use-extern-in-c-cplusplus 1/2
10/5/2020 When to use extern in C/C++

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);

https://www.tutorialspoint.com/when-to-use-extern-in-c-cplusplus 2/2

You might also like