Monday, September 27, 2010

Scope Rules of Functions in C C++

The scope rules of a language are the rules that govern whether a piece of code knows
about or has access to another piece of code or data.
Each function is a discrete block of code. A function's code is private to that function
and cannot be accessed by any statement in any other function except through a call to
that function. (For instance, you cannot use goto to jump into the middle of another
function.) The code that constitutes the body of a function is hidden from the rest of the
program and, unless it uses global variables or data, it can neither affect nor be affected by other parts of the program. Stated another way, the code and data that are defined
within one function cannot interact with the code or data defined in another function
because the two functions have a different scope.
Variables that are defined within a function are called local variables. A local
variable comes into existence when the function is entered and is destroyed upon
exit. That is, local variables cannot hold their value between function calls. The only
exception to this rule is when the variable is declared with the static storage class
specifier. This causes the compiler to treat the variable as if it were a global variable
for storage purposes, but limits its scope to within the function. (Chapter 2 covers
global and local variables in depth.)
In C (and C++) you cannot define a function within a function. This is why neither
C nor C++ are technically block-structured languages.

No comments:

Post a Comment