July 2010 Archives

Static Analyser Invariants

| No Comments

If you’re not using the Static Analyser, you should be. However, sometimes you need to give it a helping hand in order to avoid false positives. Mostly you can use assert to tell the analyser that a certain path is impossible. The problem with that is that it will usually add code to your built product. You could avoid this by defining the NDEBUG macro in your release build but I don’t like to do that (and it isn’t by default); I prefer to leave assertions in my release build. Anyway, here’s some code you can use to do the same thing as assert but won’t add any extra code to your built product. You’d use this instead of assert when it might affect performance and is also obviously always true.

#if __clang__

static void inline static_analyser_no_return (void) 
  __attribute__ ((analyzer_noreturn));

static void inline static_analyser_no_return (void) {}

/* Use this to shut the analyser up without actually adding any code. */

#define static_analyser_invariant(cond) \
  do { if (!cond) static_analyser_no_return (); } while (0)

#else

#define static_analyser_invariant(cond) ((void)0)

#endif