Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is a structure at local scope in C language?
In C, a structure defined within a function or block has local scope, meaning it is only accessible within that specific function or block. This is different from global structures that can be accessed throughout the program.
Syntax
struct tagname {
datatype member1;
datatype member2;
datatype member_n;
};
When declared inside a function, the structure definition and its variables are local to that function.
Example 1: Basic Local Structure
Here's a simple example showing a structure declared within the main() function −
#include <stdio.h>
int main() {
struct book {
int pages;
char author[30];
float price;
};
struct book b1;
b1.pages = 250;
b1.price = 29.99;
printf("Book pages: %d<br>", b1.pages);
printf("Book price: %.2f<br>", b1.price);
return 0;
}
Book pages: 250 Book price: 29.99
Example 2: Structure in Different Functions
This example demonstrates how local structures are confined to their respective functions −
#include <stdio.h>
int calculateManagerSalary() {
struct manager {
char name[20];
int age;
int salary;
};
struct manager mgr;
mgr.age = 35;
if (mgr.age > 30) {
mgr.salary = 80000;
} else {
mgr.salary = 60000;
}
return mgr.salary;
}
int main() {
struct employee {
char name[20];
int age;
int salary;
};
struct employee emp;
emp.age = 28;
emp.salary = 45000;
printf("Employee salary: %d<br>", emp.salary);
printf("Manager salary: %d<br>", calculateManagerSalary());
return 0;
}
Employee salary: 45000 Manager salary: 80000
Key Points
- Scope limitation: Local structures are only accessible within the function where they are defined.
- Memory allocation: Structure variables are created on the stack and automatically destroyed when the function exits.
- No external access: Other functions cannot directly access locally defined structure types.
Conclusion
Local scope structures in C provide encapsulation at the function level, keeping structure definitions private to specific functions. This approach is useful when a structure type is only needed within a particular function context.
