Macro(???????????)

Started by
15 comments, last by Sinner_Zero 22 years, 5 months ago
That and the publisher sems to be McGraw here.....hmmm, maybe I''m dumb.

Thnx, I think I''ll really buy that one, especially since you say ALSO and not NO JUST BUY THIS.

That and it''s cheap =)
Advertisement
Imagine you want to print what piece of code is executed as it is executed. One way to do it is to create a string mirroring the code and printing it out :

    {   foo = bar + baz;   if (debug) std::cerr << "foo = bar + baz" << std::endl;}      


However, you have to take care to keep the string and the code in synch. Well, that is what the # macro is for : it converts source code into a string that the source code can use.

          #define STRING( X ) #X{  foo = bar + baz;  if (debug) std::cerr << STRING(foo = bar + baz) << std::endl;}        



Which would not buy you much if you couldn't do things with X within the macro itself :

          #define DBG( X ) { X; if( debug ) std::cerr << #X << std::endl; } /* Executes and prints X */{   DBG( foo = bar + baz );}    


This is what is used in the assert( X ) macro. It tests the value of the expression X, and if it is false, it prints it out and abort().

Edited by - Fruny on November 17, 2001 12:10:13 AM
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
For multiline macros use a forward slash \ not a backslash - and wrap the multiple statements in a do while loop

Check out the C Language faq for details: What''s the best way to write a multi-statement macro?
late... need... more... caffeine...
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
wait, but int he macro whats the first X there for?

{X; ...}

whats that X for???
quote:Original post by Sinner_Zero
whats that X for???

To do X.

Remember that X does not necessarily have to be a single variable; it can be a statement (which the preprocessor simply substitutes in place.) For example, in Fruny''s example
foo = bar + baz 

is X. The macro therefore ensures that X is executed, and then only if debug is specified is the rest executed.
IC, X isnt really done since the macro screws it all then.

so the macro hasto actually do X, cool. this stuff is neat.

THNX a ton once again guys, the more I know. heh.

This topic is closed to new replies.

Advertisement