-4

I'm doing an introductory course to C programming, and we've just started defining macros. I'm supposed to define the macro CHECK that prints msg (a string) if cond is false, however, it doesn't print the msg to the stdout stream, whether cond is true or false. Any ideas?

1     #define CHECK(cond, msg) if(!cond) fprintf(stdout, "%s", msg)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Adrian
  • 1

2 Answers2

8

You should wrap your function-like macro like this:

#define CHECK(cond, msg)                   \
    do {                                   \
        if (!(cond)) {                     \
             fprintf(stdout, "%s", msg);   \
        }                                  \
    } while (0)

Explanation: C multi-line macro: do/while(0) vs scope block

Community
  • 1
  • 1
Marco
  • 7,007
  • 2
  • 19
  • 49
0

try wrapping it in {}:

 #define CHECK(cond, msg) {if(!cond) fprintf(stdout, "%s", msg)}

plus , make sure you really don't start with '1'

David Haim
  • 25,446
  • 3
  • 44
  • 78
  • 3
    This will lead to surprising behavior: `if (x) CHECK(cond, msg); else func();` won't work because of the extra semicolon. You have to use `do { ... } while (0)`. – Dietrich Epp Mar 14 '15 at 11:48