When I call a function X in multiple places (main, from within other functions) is it possible to know each time X was called what part of the code called it, or do I have to pass flags with each call telling the function X where it was called ?
When I call a function X in multiple places (main, from within other functions) is it possible to know each time X was called what part of the code called it, or do I have to pass flags with each call telling the function X where it was called ?
I assume you want to do this in code, rather than using development/debugging tools (which rely on support by the compiler to include information they can use).
The only way is to provide the information yourself (eg additional arguments). For example;
In C (as per 1999 standard) also supports a __func__ predefined identifier that gives the name of the calling function. This is not supported in C++ or the preceding 1989/90 C standard. There is no direct way to get the line number relative to a function; __LINE__ represents the line number in the source file.Code:#include <iostream> void func(const char *file, int line) { std::cout << "Called from source file " << file << " Line " << line << '\n'; } int main() { func(__FILE__, __LINE__); }
In C++, if you want to pass the calling function name, you have to do it yourself. For example;
Code:#include <iostream> void func(const char *caller) { std::cout << "Called by " << caller << '\n'; } int main() { const char function_name[] = "int main()"; func(function_name); }
But the real question is, why do you want to know?
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
Because I have a function that prints contents of an array, it is used multiple times.
The first line is:
what can be "created", "updated", "deleated" ...Code:cout << "Array " << what << " = ";
Right now I am passing it along with the array to the function.
So I wanted to know is there a different way to do this.
You could use something like the StackTrace class I created in this thread: http://cboard.cprogramming.com/showthread.php?t=101268
Thanks for the replys, I will stick with my original way.
But thanks for the ideas.