0

I saw the assert macro implementation which is this:

#define assert(_Expression) (void) ((!!(_Expression)) || (_wassert(_CRT_WIDE(#_Expression),_CRT_WIDE(__FILE__),__LINE__),0))

I don't understand the purpose of using the negation operator twice.

  • https://stackoverflow.com/questions/8617090/double-negation-in-c-is-it-guaranteed-to-return-0-1 or https://stackoverflow.com/questions/35847237/what-double-negation-does-in-c?noredirect=1&lq=1 – Martin Mar 09 '23 at 18:00
  • It converts an integer value into a `bool` value (although any non-zero integer value is implicitly `true` is does not have that formal value). – Weather Vane Mar 09 '23 at 18:00
  • 1
    @TomKarzes The C standard refers to `!` as "logical negation operator", so it is not wrong. – Eugene Sh. Mar 09 '23 at 18:05
  • You'll see this in JS and other more weakly-typed languages quite frequently as well. – Rogue Mar 09 '23 at 18:18
  • @user21290559, "don't understand the purpose of using the negation operator twice." --> If code had only 1 `!`, like `!(_Expression)`, would the purpose of the `!` make sense? – chux - Reinstate Monica Mar 10 '23 at 00:35
  • @chux-ReinstateMonica Yeah, if _Expression was true, then it's value would be reversed to become false which is zero. I didn't understand the purpose of switching the value to false and back to true again but I understand now thanks to the other comments. – user21290559 Mar 10 '23 at 09:18
  • @user21290559 "...and back to true again " is the error in logic. The original value was not certainly only _true_ or _false_. It could have been 0.1, a value outside the `int` range, complex, ... With `!!` the result is an `int` with a value of 0 or 1. – chux - Reinstate Monica Mar 10 '23 at 17:21

0 Answers0