views:

55

answers:

2

Background: When working with time, I wanted to pass "now" as an argument when it is known and ask the system if it is not yet known, so I passed it to an argument which as default calls the time-function. This seems to work with GCC (4.1.2) as illustrated in the following code (it looks a bit weird, but examples with time tend to be a bit more complex).

Question: Is calling a function as default argument compliant with the C++ standard / portable / reasonable practice?
Quotes from the standard, links and SO-questions are welcome

#include <iostream>
#include <string>

std::string getString()
{
  std::cout << "Default: " << std::flush;
  char line[100];
  std::cin.getline(line, 100);
  return line;
}

void printString(const std::string& str = getString())
{
  std::cout << str << std::endl;
}

int main()
{
  printString("start");
  printString();
  printString("stop");
}
+4  A: 

Yes, functions are permitted as default arguments. See the example in 8.3.6/5 of the 2003 standard

Anthony Williams
Thanks for clearing that up. I will point to here if colleagues ask what the hell I was doing.
stefaanv
+3  A: 

The C++ Programming Language (section 7.5) says:

"A default argument is type checked at the time of the function declaration and evaluated at the time of the call." (italics mine)

So it is OK to pass a function as the default argument.

Vijay Mathew