views:

48

answers:

2

Is it possible to determine the line number that calls a function without the aid of a macro?

Consider this code:

#include <iostream>

#define PrintLineWithMacro() \
  std::cout << "Line: " << __LINE__ << std::endl;   // Line 4

void PrintLine()
{
  std::cout << "Line: " << __LINE__ << std::endl;   // Line 8
}

int main(int argc, char **argv)
{
  PrintLine();           // Line 13
  PrintLineWithMacro();  // Line 14
  return 0;
}

which outputs the following:

Line: 8
Line: 14

I understand why each prints what they do. I am more interested if it's possible to mimic the macro function without using a macro.

+4  A: 

I would do the following:

#define PrintLine() PrintLine_(__LINE__)

void PrintLine_(int line) {
    std::cout << "Line: " << line << std::endl;
}

I know that this doesn't completely remove the preprocessor, but it does move most of the logic into an actual function.

sharth
This is a decent workaround, because you *have* to use a macro. However, you should explicitly qualify the function call in the macro (::PrintLine_, or whichever namespace it's in) and use parentheses.
Roger Pate
+1  A: 

Not portably. On any given platform, you could basically re-implement the details of a debugger - the information is effectively stored on your stack as the return address. You can get at that kind of thing with the backtrace() function on some platforms.

xscott