Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Macros don't respect scoping rules and operate at the textual level, as opposed to the syntax level. From this arise a number of pitfalls that can lead to strange, difficult to isolate bugs.</p> <p>Consider the following well-known example:</p> <pre><code>#define max(a, b) ((a) &lt; (b) ? (b) : (a)) ⋮ int i = max(i++, j++); </code></pre> <p>The preferred alternative in this case is a function template:</p> <pre><code>template &lt;typename T&gt; T max(const T &amp; a, const T &amp; b) { return a &lt; b ? b : a; } </code></pre> <p>Here's another case that leads to subtle problems:</p> <pre><code>#define CHECK_ERROR(ret, msg) \ if (ret != STATUS_OK) { \ fprintf(stderr, "Error %d: %s\n", ret, msg); \ exit(1); \ } ⋮ if (ready) CHECK_ERROR(try_send(packet), "Failed to send"); else enqueue(packet); </code></pre> <p>You might think that the solution is as simple as wrapping the contents of <code>CHECK_ERROR</code> in <code>{ … }</code>, but this won't compile due to the <code>;</code> before the <code>else</code>.</p> <p>To avoid the above problem (the <code>else</code> attaching to <code>CHECK_ERROR</code>'s <code>if</code> instead of the outer <code>if</code>), one should wrap such macros in <code>do … while (false)</code> as follows:</p> <pre><code>#define CHECK_ERROR(ret, msg) \ do { \ if (ret != STATUS_OK) { \ fprintf(stderr, "Error %d: %s\n", ret, msg); \ exit(1); \ } \ while (false) </code></pre> <p>This has no effect on the meaning of the macro, but ensures that the entire block is always treated as a single statement and doesn't interact in surprising ways with <code>if</code> statements.</p> <p>Long story short, macros are hazardous at many levels and should thus be used only as a last resort.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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