Code doodles #5 – quite surprising parse

I came upon a similar piece of code during an IRC discussion. While I am certain that some may consider this example trivial, I admit that the correct answer eluded me even after I verified the result with the compiler – it wasn’t until I checked the standard that it became clear.

Consider the following class:

struct foo
{
    foo()
    {
        cout << __PRETTY_FUNCTION__ << endl;
    }
 
    foo(int)
    {
        cout << __PRETTY_FUNCTION__ << endl;
    }
};

And now, consider the following code:

int global;
int main()
{
    foo();
    foo(42);
    foo(global);
}

Would you care to guess what will be printed?

Code doodles #3 – significant parentheses, C++14 style

Hello, everyone. It has been a while since my last post.

While watching CppCon 2014 I found this little gem being described by Scott Meyers.

Consider the following code:

decltype(auto) foo()
{
	static int Foo;
	return Foo;
}
 
decltype(auto) bar()
{
	static int Bar;
	return (Bar);
}
 
int main()
{
	decltype(auto) a = foo();
	decltype(auto) b = bar();
	a++;
	b++;
	cout << foo() << ", " << bar() << endl;
}

Would you expect this to print 0, 0? Well, not so fast. decltype(auto) is just a nicer syntax for decltype(name), where name is “unparenthesized id-expression or an unparenthesized class member access”, as described here. Therefore it follows the same rules.

That’s another corner case to remember, but I guess it could also make a nifty party trick, if one can find the right party.