Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Trace macros

Sometimes it s useful to print the code of each statement as it is executed, either to cout or to a trace file. Here s a preprocessor macro to accomplish this:

#define TRACE(ARG) cout << #ARG << endl; ARG

Now you can go through and surround the statements you trace with this macro. However, this can introduce problems. For example, if you take the statement:

for(int i = 0; i < 100; i++)
cout << i << endl;

and put both lines inside TRACE( ) macros, you get this:

TRACE(for(int i = 0; i < 100; i++))
TRACE( cout << i << endl;)

which expands to this:

cout << "for(int i = 0; i < 100; i++)" << endl;
for(int i = 0; i < 100; i++)
cout << "cout << i << endl;" << endl;
cout << i << endl;

which isn t exactly what you want. Thus, you must use this technique carefully.

The following is a variation on the TRACE( ) macro:

#define D(a) cout << #a "=[" << a << "]" << endl;

If you want to display an expression, you simply put it inside a call to D( ). The expression is displayed, followed by its value (assuming there s an overloaded operator << for the result type). For example, you can say D(a + b). You can use this macro any time you want to check an intermediate value.

These two macros represent the two most fundamental things you do with a debugger: trace through the code execution and display values. A good debugger is an excellent productivity tool, but sometimes debuggers are not available, or it s not convenient to use them. These techniques always work, regardless of the situation.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire