Integer to Boolean strange syntax

本文解释了一段 C++ 代码中不常见的布尔赋值语法。通过详细说明 !=0 的作用,帮助读者理解如何判断整型变量是否为非零值。

Question:

I'm less than a year into C++ development (focused on other languages prior to this) and I'm looking at a guy's code who's been doing this for two decades. I've never seen this syntax before and hopefully someone can be of some help.

bool b; // There exists a Boolean variable.
int i;  // There exists an integer variable.

sscanf(value, "%d", &i); // The int is assigned from a scan.
b = (i != 0); // I have never seen this syntax before.

I get that the boolean is being assigned from the int that was just scanned, but I don't get the (* != 0) aspects of what's going on. Could someone explain why this person who knows the language much better than I is doing syntax like this?

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.


转载于:https://www.cnblogs.com/vigorz/p/10499204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值