Puzzled by this behavior
Stefan Koch
uplink.coder at googlemail.com
Tue May 31 18:00:11 UTC 2022
On Tuesday, 31 May 2022 at 17:41:18 UTC, Don Allen wrote:
>
> ````
> import std.stdio;
>
> int main(string[] args)
> {
> void foo() {
> bar();
> }
> void bar() {
> writeln("Hello world");
> }
> foo();
> return 0;
> }
> ````
This is because you did it in a function body.
Within a function body each declaration opens a scope implicitly.
which gets closed at the end of the parent scope.
This makes sure you don't use variables before they got
initialized.
```D
int f()
{
// {
int x;
// {
int y = x; // works
// {
int y2 = z; // does not work because z not in scope
// also the value of z isn't defined yet
// {
int z;
// } } } }
}
```
function declarations within a function body follow the same
rules as variable declarations.
namely a declaration cannot forward reference another in the same
function body.
More information about the Digitalmars-d
mailing list