[英]Does && in c++ behave the same as && in Java?
my question is essentially in the title. 我的问题基本上在标题中。 Basically I've learned that in Java the && operator acts like a short circuit, so that if the first condition evaluates to false it doesn't look at the rest of the statement.
基本上我已经了解到,在Java中,&&运算符就像一个短路,所以如果第一个条件的计算结果为false,它就不会查看语句的其余部分。 I assumed this was the case in c++ but I'm writing a bit of code which first checks that an index has not exceeded a list size, then compares that index in the list to another number.
我假设这是c ++中的情况,但我正在编写一些代码,首先检查索引是否未超过列表大小,然后将列表中的索引与另一个数字进行比较。 Something like:
就像是:
//let's say list.size()=4;
for(int i=0; i<10; i++)
{
if(i < list.size() && list.get(i) == 5)
//do something
...
}
That's not the exact code but it illustrates the point. 这不是确切的代码,但它说明了重点。 I assume that since i > the list size the second half won't get evaluated.
我假设因为i>列表大小,后半部分将不会被评估。 But it appears that it still does, and I believe this is causing a Seg Fault.
但似乎它仍然存在,我相信这会导致Seg Fault。 I know I can use nested ifs but that's such an eyesore and a waste of space.
我知道我可以使用嵌套的ifs但是这样的眼睛和浪费空间。 Any help?
有帮助吗?
Yes, in C and C++ the && and || 是的,在C和C ++中是&&和|| operators short-circuit.
运营商短路。
Shortcutting works the same in C, C++, and Java. 快捷方式在C,C ++和Java中的工作方式相同。
However, given the example code, you may get a segfault if list
is null
. 但是,给定示例代码,如果
list
为null
,则可能会出现段错误。 C++ has no equivalent to Java's NullPointerException. C ++没有Java的NullPointerException。 If list might be null, you need to test for that as well.
如果list可能为null,那么您也需要测试它。
Updated The latter half of that only applies if list is a pointer. 更新后半部分仅适用于list是指针的情况。 (Which is does not appear to be.) If that was the case it would look like:
(这似乎不是。)如果是这种情况,它看起来像:
if (list && i < list->size() && list->get(i) == 5)
Yes &&
behaves similarly in Java as in C++. 是
&&
在Java中与在C ++中表现相似。 It is a short circuiting operator and also a sequence point [in C++]. 它是一个短路操作符,也是一个序列点 [在C ++中]。 The order of evaluation of operands is well defined ie from left to right.
操作数的评估顺序是明确定义的,即从左到右。
C++ && and || C ++ &&和|| operators do shortcircuiting too.
运营商也做短路。 Be careful, maybe you put a single & and C++ is using tbe binary and operator, which is not shortcircuited.
小心,也许你把一个&和C ++使用tbe二进制和运算符,它不是短路的。 Post more relevant code if you need more help.
如果您需要更多帮助,请发布更相关的代码。
C++ short circuits && and || C ++短路&&和|| just like Java.
就像Java一样。 in
if(i < list.size() && list.get(i))
, list.get(i)
will not be evaluated if i < list.size()
is false. 在
if(i < list.size() && list.get(i))
,如果i < list.size()
为false,则不会计算list.get(i)
。
The && and || &&和|| operators short-circuit if not overloaded.
如果没有过载,运营商就会短路。 I believe they can be overloaded, however, in which case they would not short-circuit if used on types for which an overload was in effect.
我相信它们可能会过载,但在这种情况下,如果在过载有效的类型上使用它们,它们就不会短路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.