Integer to Boolean strange syntax

This question already has an answer here:

  • The Definitive C++ Book Guide and List 1 answer

  • Have a read here: http://en.cppreference.com/w/cpp/language/operator_comparison

    The result of operator != is a bool. So the person is saying "compare the value in i with 0". If 'i' is not equal to 0, then the '!=' returns true.

    So in effect the value in b is "true if 'i' is anything but zero"

    EDIT: In response to the OP's comment on this, yes you could have a similar situation if you used any other operator which returns bool. Of course when used with an int type, the != means negative numbers evaluate to true. If > 0 were used then both 0 and negative numbers would evaluate to false.


    The expression (i != 0) evaluates to a boolean value, true if the expression is true (ie if i is non-zero) and false otherwise.

    This value is then assigned to b .

    You'd get the same result from b = i; , if you prefer brevity to explicitness, due to the standard boolean conversion from numeric types which gives false for zero and true for non-zero.

    Or b = (i != 0) ? true : false; b = (i != 0) ? true : false; if you like extraneous verbosity.


    (i != 0) is an expression that evaluates to true or false . Hence, b gets the value of true/false depending on the value of i .

    链接地址: http://www.djcxy.com/p/6860.html

    上一篇: 从C ++开始了解基础知识

    下一篇: 整数到布尔奇怪的语法