This code exemplifies how to insert trace statements to follow the flow of program execution. When compiler under gcc 3.3 and run, the following program will output the following trace:
trace[1]: Entering int main() trace[2]: Entering int foo(int) trace[3]: Entering int Foo::bar(int) trace[3]: i = 21 trace[3]: At line 16 in tracing_example.cpp trace[3]: Wrong answer trace[3]: i = 42 trace[3]: Exiting int Foo::bar(int) trace[3]: Entering int Foo::bar(int) trace[3]: i = 42 trace[3]: At line 13 in tracing_example.cpp trace[3]: Right answer, but no question trace[3]: i = 42 trace[3]: Exiting int Foo::bar(int) trace[2]: Exiting int foo(int) trace[1]: Exiting int main()
Of course, a word of warning must be added: adding so much tracing to your code might degrade its readability, at least until we devise an Emacs macro to hide trace statements with a couple of keystrokes.
#include <ql/quantlib.hpp> using namespace QuantLib; namespace Foo { int bar(int i) { QL_TRACE_ENTER_FUNCTION; QL_TRACE_VARIABLE(i); if (i == 42) { QL_TRACE_LOCATION; QL_TRACE("Right answer, but no question"); } else { QL_TRACE_LOCATION; QL_TRACE("Wrong answer"); i *= 2; } QL_TRACE_VARIABLE(i); QL_TRACE_EXIT_FUNCTION; return i; } } int foo(int i) { using namespace Foo; QL_TRACE_ENTER_FUNCTION; int j = bar(i); int k = bar(j); QL_TRACE_EXIT_FUNCTION; return k; } int main() { QL_TRACE_ENABLE; QL_TRACE_ENTER_FUNCTION; int i = foo(21); QL_TRACE_EXIT_FUNCTION; return 0; }