C - Identifiers in C

An identifier is the name given to a variable, function, array, or any other user-defined item in a C program.

Example:

int count;
float total;
void display();

1. Scope of Identifiers in C

Scope defines where an identifier can be accessed in a program.

Types of Scope in C

(a) Block Scope

  • Identifier is declared inside a block { }

  • Accessible only within that block

  • Typically applies to local variables

Example:

void main() {
    int x = 10;   // block scope
    printf("%d", x);
}

Here, x is accessible only inside main().


(b) Function Scope

  • Applies to function names

  • A function is visible throughout the program once declared

Example:

void display();   // function declaration

void main() {
    display();
}

void display() {
    printf("Hello");
}

(c) File (Global) Scope

  • Identifier declared outside all functions

  • Accessible to all functions in the same file

Example:

int g = 20;   // global variable

void fun() {
    printf("%d", g);
}

(d) Prototype Scope

  • Applies to function parameters in function prototypes

  • Scope exists only within the prototype

Example:

void add(int a, int b);   // a and b have prototype scope

2. Lifetime of Identifiers in C

Lifetime defines how long an identifier exists in memory during program execution.

Types of Lifetime

(a) Automatic Lifetime

  • Default for local variables

  • Created when block is entered

  • Destroyed when block exits

Example:

void fun() {
    int x = 5;   // automatic lifetime
}

(b) Static Lifetime

  • Exists throughout the entire program execution

  • Memory allocated once

  • Value is retained between function calls

Example:

void fun() {
    static int count = 0;
    count++;
    printf("%d", count);
}

(c) Global Lifetime

  • Global variables exist from program start to end

Example:

int total;   // global lifetime

(d) Dynamic Lifetime

  • Memory allocated at runtime using malloc(), calloc()

  • Exists until explicitly freed using free()

Example:

int *p = (int*)malloc(sizeof(int));
free(p);

3. Visibility of Identifiers in C

Visibility defines whether an identifier can be seen or accessed from a particular part of the program.

Visibility Rules

(a) Local Variables

  • Visible only inside the block where declared

Example:

void main() {
    int a = 10;
}

a is not visible outside main().


(b) Global Variables

  • Visible to all functions in the same file

  • Can be accessed in other files using extern

Example:

int g = 10;

void fun() {
    printf("%d", g);
}

(c) Static Variables

  • Visibility depends on where declared:

    • Inside function → visible only within that function

    • Outside function → visible only within that file

Example:

static int x = 5;   // file-level static variable