Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I create #define macro with a ternary operator with one operand that does nothing?
    primarykey
    data
    text
    <p>I am reading "No Bugs!" by David Thielen and chapter 3 discusses a way to determine if a given code path has been hit. It suggests having a macro that check an argument, and, if it is true, executes an assembly instruction that generates a specific interrupt (0x3) to create a debugger breakpoint. If the argument to the macro is false, it simply does nothing.</p> <p>The macro, then, look like this:</p> <pre><code>#ifdef DEBUG #define Trap(t) ( (t) ? __asm__("int $0x3") : ) #endif </code></pre> <p>This code, however, causes a compile error for gcc:</p> <pre><code>int_test.c:16:35: error: expected expression before ‘__asm__’ </code></pre> <p>I learned from <a href="https://stackoverflow.com/a/6118305/3047531">here</a> that because gcc's asm is a block statement and not an expression, I must use <a href="http://gcc.gnu.org/onlinedocs/gcc-4.6.0/gcc/Statement-Exprs.html" rel="nofollow noreferrer">statement expressions</a> in order to use the <strong>asm</strong> in this way. So, now it becomes:</p> <pre><code>#define Trap(t) ( (t) ? ({ __asm__("int $0x3"); }) : ) </code></pre> <p>The compiler still complains:</p> <pre><code>int_test.c:16:64: error: expected expression before ‘)’ token </code></pre> <p>Okay, so now I have to do this?</p> <pre><code>#define Trap(t) ( (t) ? ({ __asm__("int $0x3"); }) : ({ ; }) ) </code></pre> <p>That seems really dumb. Can't I just have the preprocessor insert nothing if <code>t</code> is false without using this annoying syntax?</p> <p>Note: I have left out a few other similar macros for simplicity and I have adapted the syntax from the book to work for gcc (such as replacing the book's _asm with <strong>asm</strong> as well as using AT&amp;T syntax and surrounding the assmembly in "")</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.
 

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