-1

我一直在阅读很多关于 C++ 中 ++i 和 i++ 的微优化的帖子/问题。从我了解到的是 ++i “可以”,并非总是如此,但可以比 i++ 更快。

所以这让我问这个问题,那么 i++ 有什么意义呢?我认为 ++i 是你先增加值然后返回它。在 i++ 中,您返回值然后递增它。但我对此做了一个非常简单的测试:

for(int i = 0; i < 10; ++i)
{
    std::cout << i << std::endl;
}

是相同的:

for(int i = 0; i < 10; i++)
{
    std::cout << i << std::endl;
}

两者都打印出相同的结果。所以我真正的问题是,是否存在必须使用 i++ 而不是 ++i 的情况?如果有,请解释。谢谢

4

4 回答 4

1

Here's an example:

int i = 0;
while (i++ < 10) {
    std::cout << i << std::endl;
}

This will print the numbers 1 to 10. If you used ++i, it would print 1 to 9.

Of course, this is a trivial example since there are other ways to do this, but the point is that i++ will return the old value. For further clarification:

int i = 5;
std::cout << i++ << std::endl; // 5
std::cout << i << std::endl;   // 6

std::cout << ++i << std::endl; // 7
std::cout << i << std::endl;   // 7

In a for loop, there's no difference, since the increment is executed and then the condition is checked. The only difference between the two is the value of the actual expression.

于 2013-08-31T14:08:34.033 回答
0

Sometimes you want to use the value first and then increment, e.g.

while (array[i++] != sentinel)
于 2013-08-31T14:08:06.643 回答
0

如果i++您想在递增之前获取(例如打印) ,请使用i它,例如:

for(int i = 0; i < 10; i++)
{
    std::cout << "old i = " << i++ << std::endl;
    std::cout << "new i = " << i << std::endl;
}

如果++i要打印已经增加i的 .

于 2013-08-31T14:18:59.090 回答
0

不应该存在必须使用后缀或前缀版本的可行正常情况。每个版本都可以产生相同的功能效果。

前缀运算符可以更快,但编译器无论如何都会执行优化,并且会比您手动尝试做得更好。

主要区别在于代码的可读性和简单性 - 请参阅其他答案中的示例 - 在某些情况下,前缀/后缀比其他版本更方便。

所有这些都与 C 和 C++ 相关。由于 C++ 允许您重载运算符,因此您可以为这些运算符中的每一个提供不同的功能,在这种情况下,上述声明不成立。然而,应该注意的是,编写这样的代码可能是一个非常糟糕的主意。

于 2013-08-31T14:26:28.730 回答