Something I've used but never understood is the ability in C++ to write code like:
#include <stdio.h>
void sideEffect()
{
printf("Hello, I'm a side effect\n");
}
int main()
{
printf(({sideEffect(); "Hello side effect\n";}));
return 0;
}
This prints:
Hello, I'm a side effect
Hello side effect
The ({ expr1; expr2; })
part seems to run the block and 'replace' the whole thing with the last value.
Is this is just a consequence of operator precedence that I'm not getting, or is there something else going on?
UPDATE
Something non-obvious (for me at least) is that the last expression is copied, even if it's returning a reference. I added a simple Foo class that prints when it's being copied to the example above:
...
struct Foo
{
Foo()
{}
Foo(const Foo&)
{
printf("Copying Foo...\n");
}
};
const Foo& getFoo()
{
static Foo f;
return f;
}
int main()
{
const Foo& foo = ({sideEffect(); getFoo();});
return 0;
}
The output:
Hello, I'm a side effect
Copying Foo...
If Foo is noncopyable this won't compile