1

How should I understand code like this? Especially I'm wondering what's going on in the second part of this, after '\'. Could anyone explain me how does it work?

#define except(expression, message) (void) \
(!!(expression) || (throw std::runtime_error(message), false))
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mariusz W
  • 39
  • 1
  • 8

1 Answers1

5

This is an example of taking something that should be multiple statements, and condensing it into a difficult-to-understand single statement using a couple of language rules.

The code is equivalent to this:

#define except(expression, message) \
if (!!(expression)) {} \
else { \
    throw std::runtime_error(message); \
}

The || takes advantage of short-circuiting to evaluate the RHS only if the LHS evaluates to false.

The !! is a trick to help ensure that the result is a boolean, or at least boolean-like. Traditionally, some user-defined types do not convert automatically to bool, but do provide a operator!; applying that for a second time undoes the natural negation that's implied by operator!. In the case of built-in types (e.g. integer types) it may be considered as nothing but a (pointless) explicit conversion to bool.

The , false takes advantage of the comma operator's propensity to cause the resulting expression to have the type of its RHS-most operand. You want the type of the expression to be bool so that it can be applied to the || operator, and a throw-expression has type void, so the , false corrects for that.

The cast (void) ensures that you cannot accidentally use the meaningless result of the expression as a value.

Try not to write code like this.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Great, thank you. But I still don't understand the `(!!(expression))` Why double negation? Couldn't it just be like `(expression)`? – Mariusz W Jan 29 '15 at 11:30
  • @MariuszW: I've now expanded on that for you. Really, you should be looking these things up. There is plenty of material about each language feature available even just on the internet, let alone in your C++ book. – Lightness Races in Orbit Jan 29 '15 at 11:37