Scope modifiers: Difference between revisions

(Added zkl)
(→‎{{header|C}}: Added bc)
Line 146:
var2$ = "Global2"
</pre>
 
=={{header|bc}}==
All identifiers are global by default (except function parameters which are local to the function). There is one scope modifier: <code>auto</code>. All identifiers following the <code>auto</code> statement are local to the function and it must be the first statement inside the function body if it is used. Furthermore there can only be one <code>auto</code> per function.
 
It's important to understand, that all function parameters and local identifiers are pushed onto a stack when entering the function and thus hide the values of identifiers with the same name from the outer scope. They are popped from the stock when the functions returns. Thus it is possible that a function which is called from another function has access to the local identifiers and parameters of its caller if itself doesn't use the same name as a local identifier.
 
<lang bc>define g(a) {
auto b
b = 3
 
"Inside g: a = "; a
"Inside g: b = "; b
"Inside g: c = "; c
"Inside g: d = "; d
 
a = 3; b = 3; c = 3; d = 3
}
 
define f(a) {
auto b, c
 
b = 2; c = 2
"Inside f (before call): a = "; a
"Inside f (before call): b = "; b
"Inside f (before call): c = "; c
"Inside f (before call): d = "; d
x = g(2) /* Assignment prevents output of the return value */
"Inside f (after call): a = "; a
"Inside f (after call): b = "; b
"Inside f (after call): c = "; c
"Inside f (after call): d = "; d
 
a = 2; b = 2; c = 2; d = 2
}
 
a = 1; b = 1; c = 1; d = 1
"Global scope (before call): a = "; a
"Global scope (before call): b = "; b
"Global scope (before call): c = "; c
"Global scope (before call): d = "; d
x = f(1)
"Global scope (before call): a = "; a
"Global scope (before call): b = "; b
"Global scope (before call): c = "; c
"Global scope (before call): d = "; d</lang>
 
{{Out}}
<pre>Global scope (before call): a = 1
Global scope (before call): b = 1
Global scope (before call): c = 1
Global scope (before call): d = 1
Inside f (before call): a = 1
Inside f (before call): b = 2
Inside f (before call): c = 2
Inside f (before call): d = 1
Inside g: a = 2
Inside g: b = 3
Inside g: c = 2
Inside g: d = 1
Inside f (after call): a = 1
Inside f (after call): b = 2
Inside f (after call): c = 3
Inside f (after call): d = 3
Global scope (before call): a = 1
Global scope (before call): b = 1
Global scope (before call): c = 1
Global scope (before call): d = 2</pre>
 
=={{header|C}}==