在某些情况下,使用位与比较的更好样式?

发布于 2025-02-11 16:39:57 字数 190 浏览 4 评论 0原文

只是想知道编写这样的代码是否更好/更有效:

if (bitset[index] & 1)
{
//do something
}

vs:

if (bitset[index] == 1)
{
//do something
}

谢谢!

Just wondering if it's better style/more efficient to write code like this:

if (bitset[index] & 1)
{
//do something
}

vs:

if (bitset[index] == 1)
{
//do something
}

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

£烟消云散 2025-02-18 16:39:57

以上都不是。从评论中,您是在谈论诸如C ++的std :: bitset之类的内容,其operator []返回bool。通常,布尔值仅与其他布尔值一起运行,使用布尔操作(&&&||等) 。将其与另一种类型的对象(例如整数1)进行比较,或者应用整数算术操作(例如&)似乎很奇怪。 | + -等。语言的转换规则让您做到这一点,但逻辑上没有那么多的意义。

因此,最惯用的,也是最紧凑的版本是:

if (bitset[index]) {
    // ...
}

如果将测试视为平等比较的上下文更有意义,那么您可以:

if (bitset[index] == true) {
    // ...
}

但是,对于大多数C ++程序员来说,这看起来简直是多余的。

从优化的角度来看,这都是无关紧要的。任何合理的编译器都会意识到它们都是等效的,并优化它们的所有相同。但是,通常,如果您要做的事情,那么通常会通过以最常见和惯用的方式编写它来获得最佳的优化,因为那是编译器最有可能处理的方法。

None of the above. From the comments, you are talking about something like C++'s std::bitset, whose operator[] returns bool. Normally, boolean values are only operated together with other boolean values, using boolean operations (&&, ||, !, etc). It seems strange to compare it with an object of another type (e.g. the integer 1), or to apply integer arithmetic operations like & | + - etc. The conversion rules of the language let you do it, but it doesn't make as much logical sense.

So the most idiomatic, and also most compact, version would be:

if (bitset[index]) {
    // ...
}

If it makes more sense in context to think of the test as an equality comparison, then you can:

if (bitset[index] == true) {
    // ...
}

but to most C++ programmers this would simply look redundant.

This is all irrelevant from the standpoint of optimization; any reasonable compiler will realize that they are all equivalent and optimize them all the same. In general, though, if you're doing something common, then you will usually get the best optimization by writing it in the most common and idiomatic way, as that is what the compiler is most likely to handle well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文