Defining double exclamation?

前端 未结 7 1938
失恋的感觉
失恋的感觉 2021-02-04 06:43

I understand what a double exclamation mark does (or I think I understand) but I am not sure how it is defined on a random object. For example in the code snippet below:

7条回答
  •  野性不改
    2021-02-04 07:06

    There is no "!!" operator, so in fact, the statement is equivalent to:

    hasSolution = !(!a);

    So first, operator!() is called on expression "a", then another operator!() is called on the result. In the case of our code, "a" is a pointer to Assignement. C++ defines a special case for using operator!() on a pointer type: it returns a bool which is true if the pointer is null and false otherwise. In short, the same as the expression (a == 0). Calling operator!() on the result of (!a), which is a bool, simply reverts the result, i.e. returns true if (!a) is false and false if (!a) is true.

    So in conclusion, (!!a) return the same result as (a != 0). This is because "a" is a pointer.

提交回复
热议问题