Skip to content

Instantly share code, notes, and snippets.

@mjhanninen
Created August 7, 2015 16:56
Show Gist options
  • Save mjhanninen/a0bead288232fb9f8cca to your computer and use it in GitHub Desktop.
Save mjhanninen/a0bead288232fb9f8cca to your computer and use it in GitHub Desktop.
Default value for non-const reference argument
// $ clang++ --std=c++11 defaultref.cpp
// $ ./a.out
// Calling without the default argument:
//
// foo in main pre-increment = xyzzy
// foo in main post-incement = yzxxz
// foo in withFoo pre-increment = yzxxz
// foo in withFoo post-increment = zxyyx
// foo in main post-withFoo = zxyyx
//
// Calling with the default argument:
//
// defaultFoo in main pre-increment = xyzzy
// defaultFoo in main post-incement = yzxxz
// foo in withFoo pre-increment = yzxxz
// foo in withFoo post-increment = zxyyx
// defaultFoo in main post-withFoo = zxyyx
#include <iostream>
enum class Foo
{
xyzzy,
yzxxz,
zxyyx
};
std::ostream &
operator<<(std::ostream &o, Foo &foo)
{
switch (foo)
{
case Foo::xyzzy:
o << "xyzzy";
break;
case Foo::yzxxz:
o << "yzxxz";
break;
case Foo::zxyyx:
o << "zxyyx";
break;
}
return o;
}
Foo &
operator++(Foo &foo)
{
switch (foo)
{
case Foo::xyzzy:
foo = Foo::yzxxz;
break;
case Foo::yzxxz:
foo = Foo::zxyyx;
break;
case Foo::zxyyx:
foo = Foo::xyzzy;
break;
}
return foo;
}
static Foo defaultFoo = Foo::xyzzy;
void
withFoo(Foo &foo = defaultFoo)
{
std::cout << "foo in withFoo pre-increment = " << foo << std::endl;
++foo;
std::cout << "foo in withFoo post-increment = " << foo << std::endl;
}
int
main()
{
std::cout << "Calling without the default argument:" << std::endl
<< std::endl;
Foo foo = Foo::xyzzy;
std::cout << "foo in main pre-increment = " << foo << std::endl;
++foo;
std::cout << "foo in main post-incement = " << foo << std::endl;
withFoo(foo);
std::cout << "foo in main post-withFoo = " << foo << std::endl;
std::cout << std::endl
<< "Calling with the default argument:" << std::endl
<< std::endl;
std::cout << "defaultFoo in main pre-increment = " << defaultFoo << std::endl;
++defaultFoo;
std::cout << "defaultFoo in main post-incement = " << defaultFoo << std::endl;
withFoo();
std::cout << "defaultFoo in main post-withFoo = " << defaultFoo << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment