Scope rule in C:
There are basically three scope rules:
- Local Scope
- Global Scope
- Function Prototype Scope
Local Scope:
For Example:
#include <stdio.h>
int main()
{
{
int x = 9, y = 90;
{
/* The outer block contains declaration of x and Y,
* so following statement is valid and prints 9 and 90 */
printf("Value of x = %d, and y = %d\n", x, y);
{
/* y is declared again, so outer block y is not accessible
* in this block */
int y = 99;
/* Let's change the outer block variable x to 10 */
x++;
/* Now let's change this block's variable y to 100 */
y++;
printf("Value of x = %d, y = %d\n", x, y);
}
/* This statement will accesses only outer block's variables */
printf(" Value of x = %d, y = %d\n", x, y);
}
}
return 0;
}
Output:
Value of x = 9, and y = 90
Value of x = 10, and y = 100
Value of x = 9, and y = 90
Output:
Value of x = 9, and y = 90
Value of x = 10, and y = 100
Value of x = 9, and y = 90
Global Scope:
Example 1 | Global Variable
/* C program to illustrate the global scope of variables */
#include <stdio.h>
/* Global variable */
int x = 9;
/* Accessing global variable x within a display() function */
void display()
{
printf("%d\n", x);
}
/* main function */
int main()
{
/* Let's print the value of globla variable x before
* changing it form main() */
printf("Before changing the value of x = %d", display());
/* Now let's change the value of global variable x
* from main(), then call display() function. */
x = 99;
printf("After changing the value of x = %d", display());
}
Output:
Before changing the Value of x = 9
After changing the value of x = 99
Output:
Before changing the Value of x = 9
After changing the value of x = 99
Example 2: | Global Variable
/* filename: file1.c */
int a;
int main(void)
{
a = 2;
}
/* filename: file2.c, When this file is linked with file1.c -
* function of this file can access the global variable 'a' */
extern int a;
int myfun()
{
a = 2;
}
Next to be updated soon...
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.