How is this code invalid?

ag0aep6g anonymous at example.com
Sat Dec 17 00:48:23 UTC 2022


On Saturday, 17 December 2022 at 00:23:32 UTC, thebluepandabear 
wrote:
> ```D
> int[] numbersForLaterUse;
>
> void foo(int[] numbers...) {
>    numbersForLaterUse = numbers;
> }
>
> struct S {
>   string[] namesForLaterUse;
>
>   void foo(string[] names...) {
>      namesForLaterUse = names;
>   }
> }
> ```
[...]
> The thing is, when I run the code I get absolutely no error, so 
> how is this exactly a 'bug' if the code runs properly? That's 
> what I am confused about. What is the D compiler doing behind 
> the scenes?

You're witnessing the wonders of undefined behavior. Invalid code 
can still produce the results you're hoping for, or it can 
produce garbage results, or it can crash, or it can do something 
else entirely. And just because running it once does one thing, 
does not mean that the next run will do the same.

For your particular code, here is an example where 
`numberForLaterUse` end up not being what we pass in:

```d
int[] numbersForLaterUse;

void foo(int[] numbers...) {
    numbersForLaterUse = numbers; /* No! Don't! Bad programmer! 
Bad! */
}

void bar()
{
     int[3] n = [1, 2, 3];
     foo(n);
}

void main()
{
     bar();
     import std.stdio;
     writeln(numbersForLaterUse); /* prints garbage */
}
```

But again nothing at all is actually guaranteed about what that 
program does. It exhibits undefined behavior. So it could just as 
well print "[1, 2, 3]", making you think that everything is fine.


More information about the Digitalmars-d-learn mailing list