Open In App
Related Articles

Internal static variable vs. External static variable with Examples in C

Improve Article
Improve
Save Article
Save
Like Article
Like

The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments.

Internal Static Variables

Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function.

Syntax:

 main( ) 
{
  static datatype variable;
  // other statements
}

Example:

C




// C program to demonstrate
// Internal Static Variables
 
#include <stdio.h>
 
int value();
 
int main()
{
    printf("%d", value());
    return 0;
}
 
int value()
{
    static int a = 5;
    return a;
}

Output

5

External Static Variables

External Static variables are those which are declared outside a function and set globally for the entire file/program.

Syntax:

 
static datatype variable;

main()
{
  statements
}

function1()
{
  statements
}

Example:

C




// C program to demonstrate
// External Static Variables
 
#include <stdio.h>
 
int add(int, int);
 
static int a = 5;
 
int main()
{
    int c;
    printf("%d", add(a, c));
}
 
int add(int c, int b)
{
    b = 5;
    c = a + b;
    return c;
}

Output

10

Difference between Internal Static Variables and External Static Variables

Following are some major differences between internal static and external static variables:

ParameterInternal Static VariablesExternal Static Variables
Keyword”static””static”
LinkageInternal static variable has internal linkage.External static variables has internal linkage.
DeclarationInternal static variables are declared within a function.External static variables are declared outside any function.
ComparisonInternal static variables are local variables.External static variables are similar to global variables.
VisibilityInternal static variables are accessible only in their particular function.External Static variables are accessible only from within the file of their declaration.
LifetimeThe storage duration of Internal static variables is throughout the whole program.The storage duration of external static variables is throughout the whole program.
ScopeFunction of the variable’s declaration.File of the variable’s declaration.

Last Updated : 05 Sep, 2023
Like Article
Save Article
Similar Reads