What does scope of functions mean?
I understand the scope of variables. When we talk about the scope of functions, is it referred to the functions within structures (classes) or is there scope for the normal functions that we call in main()
of a C/C++ program?
Functions can have global, namespace, class (usually called members in that case), or local (within another function) scope. They can also be
static
giving them internal linkage or within an anonymous namespace, making them inaccessible outside a translation unit (while still having external linkage so they can be used as template parameters).Loosely speaking, a scope is a region in which names can be declared. Names declared in a scope are accessible within that scope and, in some circumstances, also from outside.
(To be pedantically accurate, that is actually a declaration region, and the scope of a name is the part of the program in which the name is valid. It begins where it's declared, and includes the rest of that region and, sometimes, some other regions.)
Scopes are introduced by namespaces, classes, and compound statements (that is, blocks of code statements surrounded by
{}
). The last one includes the bodies of functions.Most objects and functions have names, and each of these names is inside a scope.
So the "scope of a function" could mean two things: either the scope defined by the function's body, in which its local variables are declared; or the scope (either a class or a namespace) in which the function name is declared.
UPDATE: you say you mean the scope of the function name. This always begins immediately after the declaration; where it ends depends on where that declaration was.
I think what is meant here is the scope in which Labels (A Label is what you use with
goto
statements) are visible.Maybe this article could also help you understand scopes. You can also take a look at this question on stackoverflow.
Yes, functions have scope as well, though their scope is generally larger than that of most variables.
In C [edit: which was one of the tags when I wrote this], functions have either global scope or file scope. Global scope applies to a normal function that's visible throughout the entire program. File scope applies to a function you've marked as "static", so it's only visible within the same translation unit.
C++ uses slightly different names for those, but has the same basic concepts. It adds namespaces in the form of the things actually named "namespace" and
struct
s/class
es. With one exception, a function in a namespace is visible only within that namespace. The exception is if you define afriend
function inside aclass
/struct
:In this case, even though the function is defined inside of
X
, its name is injected into the surrounding namespace so it's visible outside of X.