Is there anyway to get the calling function?
ie

void A()
{
if (A() was called from B() )
 do something;
else
 do something else
}

Is this possible?

Dave

Recommended Answers

All 4 Replies

No, and even if it were possible, it would be completely counterintuitive.

Also, it's completely unnecessary. Instead, pass a parameter that tells how you want the function to behave.

It's not that counterintuitive. I'm using some minimization software that calls my function a whole bunch of times. In those cases, I don't want to output anything to the screen. But if I call my function manually (from main() for example), then I would like to see some output. It is a restriction of the library that the function must only take certain parameters, so it is not possible to simply pass a flag as you suggest.

Dave

You can get 99% of what you want (if I understand correctly)

You declare a global variable, say outputFlag (or put it in a namespace when doing it properly) and have the function check that. Ugly but gets the job done.

Also have a wrapper function (which takes the flag) and then calls the required function after setting the outputFlag variable.

If you can't touch the function itself (i.e. it is in a library), then buffering the output, and discarding/printing is an ugly solution, but it is ugly and can have side effects on errors etc.

The other slightly more sophisticated way is to stream all your output through a logger, then the logger can be set to take care of the output/no-output calls. But for one function I wouldn't bother, but for several it is starting to look like a better idea.

There are some platform specific methods of getting the backtrace call, but normally that also involves leaving a level of debug trace and limiting the optimization, and they are REALLY messy.

It's not that counterintuitive.

Yes it is. Having functions secretly behave differently depending on invisible environmental variables is tremendously counterintuitive.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.