Using Local and Global Structures in C Programming
In C programming, a structure can be defined as a local or global variable depending on where it is declared and initialized. A local structure is defined inside a function or a block of code, and it can only be accessed within that function or block of code.
- This program is an example of how to use local and global structures in C. It defines a global structure called "student" with three members: name (a character pointer), age (an integer), and per (a float).
- In the main function, it creates a variable of the struct student type "o". Then it assigns values to the members of the "o" struct variable. The member 'name' is assigned with a string "Tutor Joes" and 'age' is assigned with 30 and 'per' is assigned with 85.5
- Then it uses the printf statement to print the values of the members of the "o" struct variable using the dot operator (.) to access them.
- The program also defines a function total(), which defines a local structure called "mark", with three members: m1, m2, and m3 (all integers).
- It creates a variable of the struct mark type "s" and assigns values to its members m1, m2, m3. Then it uses the printf statement to print the values of the members of the "s" struct variable.
- Finally, it calls the total() function from main function
- It's important to note that in the struct student the member 'name' is defined as a pointer to char, so it holds the address of the string "Tutor Joes" in memory. Also, the struct mark is defined inside the function total() and it's a local variable, it can only be accessed within this function.
Source Code
//Local and Global Scope Structure in C Programming
#include<stdio.h>
struct student
{
char *name;
int age;
float per;
};
void total()
{
struct mark
{
int m1,m2,m3;
}s;
s.m1=50;
s.m2=50;
s.m3=50;
printf("\nMark-1 : %d",s.m1);
printf("\nMark-2 : %d",s.m2);
printf("\nMark-3 : %d",s.m3);
}
int main()
{
struct student o;
//struct mark x;
o.name="Tutor Joes";
o.age=30;
o.per=85.5;
printf("\nName : %s",o.name);
printf("\nAge : %d",o.age);
printf("\nPercent : %f",o.per);
total();
return 0;
}
To download raw file
Click Here
Output
Name : Tutor Joes
Age : 30
Percent : 85.500000
Mark-1 : 50
Mark-2 : 50
Mark-3 : 50