Functions and Scope in C++
A function should have a readily grasped purpose as indicated by the function name, for example print()
, which is clear as to intent. Do not obscure what a function does by giving it unrelated tasks.
For example, if you want to print an array and find its maximum element, write two different functions.
In C++, there is little need for untyped functions with the ellipsis signature. Functions of appropriate type can be overloaded or generated from templates. This leads to type safety, which the compiler can statically test for.
Overloading, however, is frequently overused, making code difficult to follow and debug. In the extreme, by using function foo()
with different signatures, one can produce any computation--clearly a poor practice.
Scope Rules of Functions
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. The code of a function 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 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.
In C (and C++) you cannot define a function within a function.
This is why neither C nor C++ are technically block-structured languages.