Modern C++ has a lot of features that can be used in professional programming. C++11 standard improved the previous C99 standard feature __func__
which is a predefined identifier for functions or methods. The predefined identifier __func__
returns as a string that contains the name of the enclosing function or method. In this post, we explain how we can use predefined identifier __func__
in modern C++.
What is the predefined identifier __func__ in C++?
The predefined identifier __func__
returns as a string that contains the name of the enclosing function or method. In other words, it returns the string that contains the name of the function that is called from. This basic feature from C99 requires some modification to integrate with C++, and with C++11 it is improved to support strings in addition to char arrays. This a kind of constant string and the syntax is as below,
1 2 3 |
__func__ |
and here is a simple example to display function name:
1 2 3 4 5 6 |
void MyAwesomeFunction() { std::cout << "Called from: " << __func__ << std::endl; } |
and when we run this function, it will print out its name as below.
1 2 3 |
Called from: MyAwesomeFunction |
Is there a full example about the predefined identifier __func__ in C++?
Here is a full example about the predefined identifier __func__
in modern C++. In this example, we used __func__
in both function and method,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> void MyAwesomeFunction() { std::cout << "Called from: " << __func__ << std::endl; } class Tx { public: void MyLovelyMethod() { std::cout << "Called by: " << __func__ << std::endl; } }; int main() { Tx obj; MyAwesomeFunction(); // using __func__ in function obj.MyLovelyMethod(); // using __func__ in method system("pause"); return 0; } |
here is the output,
1 2 3 4 |
Called from: MyAwesomeFunction Called by: MyLovelyMethod |
This feature is generally used to capture function names as string literals and to assist diagnostic libraries. Sometimes we want to know the name of the function that is called, you can decide some sub operations by the function that is called.
For more information on this feature, see Adoption of C99’s __func__ and __func__ predefined identifier Proposal document.
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.