Scope and Extent in C Programming Part-2



BLOCK SCOPE
                 A variable with block scope cannot be accessed outside the block in which it is defined. This limitation is really an advantage since it protects the variable from inadvertent side effects. By limiting the region over which variables can be seen, you reduce the complexity of a program, making it more readable and maintainable. Block scoping allows you to write section of code without worrying about whether the variable names conflict with name used in other parts of the program.
                This feature can be useful when you want to add some debugging code into a function. By creating a new block and declaring variables within it, you eliminate the possibility of naming conflicts. In addition, if you delete the debugging code at a later date, you need not look at the top of the function to find variable declarations that also need to be deleted.






FUNCTION SCOPE
               The only names that have function scope are goto labels. Labels are active from the beginning to the end of a function. This means that labels must be unique within a function. Different functions, however may use the same label names without creating conflicts.

FILE and PROGRAM SCOPE
             Giving a variable FILE SCOPE makes the variable active throughout the rest of the file. So, if a file contains more than one function, all of the function following the declaration is able to use the variable. To give a variable file scope, declare it outside a function with the static keyword.
             Variables with program scope, called global variables, are visible to routines in other files as well as their own file. To create a global variable, declare it outside a function without the static keyword. In the following program segment, j has program scope and k has file scope. Both variable can be accessed by routines in the same file, but only j can be accessed by routines in other files.
int  j;
static  int  k;
main()
{
----------
----------   }
          Variables with file scope are particularly useful when you have a number of function that operate on a shared data structure, but you do not want to make the data available to other function. A file that contains this group of function is often called a module.
Scope and Extent in C Programming Part-2 Scope and Extent in C Programming Part-2 Reviewed by vijay pratap singh on July 03, 2017 Rating: 5

No comments:

Powered by Blogger.