Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make a C++ macro behave like a function?
    primarykey
    data
    text
    <p>Let's say that for some reason you need to write a macro: <code>MACRO(X,Y)</code>. <strong>(Let's assume there's a good reason you can't use an inline function.)</strong> You want this macro to emulate a call to a function with no return value.</p> <hr> <h3>Example 1: This should work as expected.</h3> <pre><code>if (x &gt; y) MACRO(x, y); do_something(); </code></pre> <h3>Example 2: This should not result in a compiler error.</h3> <pre><code>if (x &gt; y) MACRO(x, y); else MACRO(y - x, x - y); </code></pre> <h3>Example 3: This should <em>not</em> compile.</h3> <pre><code>do_something(); MACRO(x, y) do_something(); </code></pre> <hr> <p>The naïve way to write the macro is like this:</p> <pre><code>#define MACRO(X,Y) \ cout &lt;&lt; "1st arg is:" &lt;&lt; (X) &lt;&lt; endl; \ cout &lt;&lt; "2nd arg is:" &lt;&lt; (Y) &lt;&lt; endl; \ cout &lt;&lt; "Sum is:" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; </code></pre> <p>This is a very bad solution which fails all three examples, and I shouldn't need to explain why.</p> <p><strong>Ignore what the macro actually does, that's not the point.</strong></p> <hr> <p>Now, the way I most often see macros written is to enclose them in curly braces, like this:</p> <pre><code>#define MACRO(X,Y) \ { \ cout &lt;&lt; "1st arg is:" &lt;&lt; (X) &lt;&lt; endl; \ cout &lt;&lt; "2nd arg is:" &lt;&lt; (Y) &lt;&lt; endl; \ cout &lt;&lt; "Sum is:" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; \ } </code></pre> <p>This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon.</p> <hr> <p>Is there a way to write a macro so that it pass all three examples?</p> <hr> <p><i>Note: I am submitting my own answer as part of the <a href="https://stackoverflow.com/questions/162246/is-stack-overflow-appropriate-for-sharing-knowledge-tips-tricks-and-interesting">accepted way of sharing a tip</a>, but if anyone has a better solution feel free to post it here, it may get more votes than my method. :)</i></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload