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
Example:
void display(); // function declaration
void main() {
display();
}
void display() {
printf("Hello");
}
(c) File (Global) Scope
Example:
int g = 20; // global variable
void fun() {
printf("%d", g);
}
(d) Prototype Scope
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
Example:
void fun() {
static int count = 0;
count++;
printf("%d", count);
}
(c) Global Lifetime
Example:
int total; // global lifetime
(d) Dynamic Lifetime
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
Example:
void main() {
int a = 10;
}
a is not visible outside main().
(b) Global Variables
Example:
int g = 10;
void fun() {
printf("%d", g);
}
(c) Static Variables
Example:
static int x = 5; // file-level static variable