
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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
#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);
- Related Articles
- Why do we use extern "C" in C++ code?
- “extern” keyword in C
- Name Mangling and extern “C” in C++
- The extern storage class in C++
- When to use inline function and when not to use it in C/C++?
- When to use tuples in C#?
- What is the effect of extern “C” in C++?
- When to use virtual destructors in C++?
- What is an extern storage class in C language?
- When to use references vs. pointers in C/C++
- When to use i++ or ++i in C++?
- When to use C over C++, and C++ over C?
- When to use new operator in C++ and when it should not be used?
- When to use an abstract class and when to use an interface in Java?
- When can I use a forward declaration in C/C++?
