Little quiz

Jesse Phillips jessekphillips+D at gmail.com
Thu Mar 24 19:53:10 PDT 2011


bearophile Wrote:

> A little quiz for people here: guess the output of this little D2 program (it compiles correctly and doesn't crash at run time, so it's a fair question):
> 
> 
> import std.typecons: tuple;
> import std.c.stdio: printf;
> 
> auto foo() {
>     printf("foo\n");
>     return tuple(1, 2);
> }
> 
> void main() {
>     foreach (x; foo().tupleof)
>         printf("%d\n", x);
> }

Starting from main. As we are performing a foreach over a tuple this will need to happen at compilation. As their are many bugs with compile time foreach I would think this code evaluates to nothing and thus the program prints nothing.

However if that is working then I would expect foo() to be executed at compile-time which would mean 'foo' might be printed during compilation. As tupleof is supposed to return a type tuple, I'm unsure what gibberish printing it as a decimal would do.

The other likely possibility is that the foreach is unrolled into code like:

x = foo().tupleof[0]
print...
x = foo().tupleof[1]
print...

where .tupleof is some other fancy runtime thing. In this case you would get foo\nnumber\nfoo\nnumber...

------

So yeah, from that code I have no idea what it is supposed to do. But I am not surprised by its behavior.



More information about the Digitalmars-d-learn mailing list