简体   繁体   English

类 Python || 和 && for if 在 C++ 中

[英]Python-like || and && for if in C++

Is the following Python-like construct slower in C++?以下类似 Python 的构造在 C++ 中是否较慢?

bool_stuff[i] || (a[i]=1);

compared the plain old比较普通的旧

if(!bool_stuff[i])
  a[i]=1;

The reason is, I have the above snippet in a nested for loop with this being the only statement.原因是,我在嵌套的for循环中有上面的代码片段,这是唯一的语句。 I think the readability is greater in the former case, but shall use the latter only if the former is not safe or if it is slow.我认为前者的可读性更好,但只有在前者不安全或速度慢时才应使用后者。

They compile to the same thing (If you use any optimisation above -O0 in gcc, and probably in other compilers).它们编译为相同的东西(如果您在 gcc 中使用-O0以上的任何优化,并且可能在其他编译器中使用)。

Other disadvantages of the first method is that the expression on the right has to be convertible to a bool (Calling operator bool if it has side effects for no reason), and, if operator||第一种方法的其他缺点是右边的表达式必须可以转换为bool (如果它无故有副作用,则调用operator bool ),并且,如果operator|| is overloaded, it will not actually short circuit.过载,它实际上不会短路。

The if statement is much more readable and the same speed. if语句更具可读性且速度相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM