Pages

Saturday, February 13, 2010

Retrieve function name programmatically (__FILE__, __FUNCTION__, __LINE__)

Macros __FUNCTION__ allows to retrieve the function name at run-time:
#include <iostream>
using namespace std;

void funct1()
{
cout << __FUNCTION__ << endl;
}

void funct2()
{
cout << __FUNCTION__ << endl;
}

int main()
{
funct1();
funct2();

if (strcmp(__FUNCTION__, "main") == 0)
{
cout << "main()" << endl;
}
return 0;
}
How I understand this feature was added in C99:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1642.html

It makes sense to mention two other mocros: __LINE__ and __FILE__
Here is a simple example:
#include <iostream>
using namespace std;

int main()
{
cout << "file name: " << __FILE__ << endl;
cout << "line number: " << __LINE__ << endl;

int x = 2 * __LINE__;
cout << "x = 2 * __LINE__ = " << x;
return 0;
}

Of course it works with the classes:
#include <iostream>
using namespace std;

class A
{
public:
A()
{
cout << __FUNCTION__ << endl;
}

~A()
{
cout << __FUNCTION__ << endl;
}
};

int main()
{
A a;
return 0;
}

No comments:

Post a Comment