Is ++i faster than i++ in C++?

Recently, I am preparing to attack Likou, and of course it has just begun. I plan to make a thought summary every 50 questions. But in the process of doing it recently, I found a problem, that is, the for loop often given by the official solution is ++i, including other people's solution, the same use of ++i, I am very confused here, is it ++ Is i faster than i++? Otherwise, I should see both writing methods in the solution, but almost all I see are ++i, so obviously, there is a problem!


Without further ado, let's start with the dry goods.

The difference between ++i and i++

To put it simply, we all know that ++iit is self-incrementing first, and then computing. Instead,i++ it is calculated first and then incremented.

Here is an interesting phenomenon:

#include <iostream>
using namespace std;
int main()
{
    
    
    int a = 0;
    int b = 0;
    int *c = &(a++);
    int *d = &(++b);
    return 0;
}

Error reported after compilation

main.cpp:7:19: error: lvalue required as unary ‘&’ operand
     int *c = &(a++);

& acts on an lvalue, a++not an lvalue, but ++bthe result of is an lvalue.

Easy to understand lvalue and rvalue

  • lvalue: named object, assignable
  • Rvalue, temporary object, not assignable

It means that a++it is an rvalue, or "temporary object", why is this?

We can look at the principle of operator overloading

class Test
{
    
    
public:
    Test& operator++();//前置自增
    const Test operator++(int);//后置自增
private:
    int curPos; //当前位置
};
/*前置自增实现范式*/
Test& Test::operator++()
{
    
    
    ++curPos;      //自增
    return *this;  //取值
}
/*后置自增实现范式,为了与前置区分开,多了一个int参数,但从来没用过*/
const Test Test::operator++(int)
{
    
    
    Test tmp = *this;  //取值
    ++curPos;             //自增
    return tmp;
}

We can see that although the value of curPos is auto-incremented after post-increment, it returns a temporary object, and the next call will be the value of curPos at the current moment.

So in C++, ++i is faster than i++. If possible, try to use ++i for auto-increment in programming.


The old rules are useful Erlian, thank you everyone.

Guess you like

Origin blog.csdn.net/suren_jun/article/details/127595685