tags:

views:

152

answers:

2
int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    system("pause");
    return main();
}

The above works,but it hardcoded the main(),is there a magic variable to get the current running function?

+4  A: 

The C++ Standard says that you may not call main() from your own code. As for getting the name of the current function, you could use the __FUNCTION__ macro, but once again this is not standard:

#include <iostream>
using namespace std;

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

int main() {
   foo();
}

should print "foo" or something similar if __FUNCTION__ is supported.

anon
@Neil, \_\_FUNCTION\_\_ is going to be string... it cannot be invoked.
Michael Aaron Safyan
@Michael I know. I wasn't clear (not for the first time) what @Mask was actually asking about. The above is about as good as you are going to get as regards function metadata.
anon
In terms of metadata, \_\_func\_\_ will soon be standard.
Michael Aaron Safyan
Well, if you're going to assume non-standard `__FUNCTION__`, then you could also assume non-standard `dlopen` and `dlsym` (or equivalent), and get a function pointer that way...
Steve Jessop
A: 

Generally, no. For now it will be enough for you to know that the compiler needs to know the exact function you're calling at the compile time. You cannot do magic like, let's say

func = "my_function"; 
func(); 

if the called function name will change during runtime. (There are exceptions and ways around that, but you don't need that).

Don't think about that as a case of hard-coding: it is not. If you need to call the function, then you just write its name, and don't try to abstract it, or something.

Also, now would be a nice way to learn about the while loop, infinite loops and write without the function calls at all, e.g

int main()
{
    while (1) {
        cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
        system("pause");
    }
}
Einar Lielmanis