C: Efficient use of macros

#ifndef MACROS_NULLCHECK_H_
#define MACROS_NULLCHECK_H_

#include <assert.h>

#define NULLCHECK(x) assert(x != (void *) 0);

#endif

If I used this style as a template for declaring macros, what conditions would you have?

+3
source share
6 answers
  • puts brackets around the argument (it prevents problems when passing expressions)

  • do not put it; at the end (use will be more natural)

    #define NULLCHECK (x) assert ((x)! = (void *) 0)

+14
source

One change I could make is to comment on the closure #endif:

#endif  // MACROS_NULLCHECK_H_

This makes it easier to understand what this one does #endifwhen the file is larger than the screen.

+3
source

, , ..

assert((x) != (void*) 0)

, , ( ), , .

, ,

NULLCHECK(pSomething);

C- .

+3

- CERT C Secure Wiki:

PRE00-.
PRE01-.
PRE02-. PRE03-. typedefs
PRE10-. do-while
PRE11-.
PRE31-. , , , ,
PRE32-.

+1

. , .

0
source

To enforce ;, use

#define NULLCHECK(x) do { assert((X)); } while (0)
0
source

Source: https://habr.com/ru/post/1717336/


All Articles