Is there a performance difference between i++ and ++i in C++?

前端 未结 17 2325
臣服心动
臣服心动 2020-11-21 17:15

We have the question is there a performance difference between i++ and ++i in C?

What\'s the answer for C++?

17条回答
  •  野的像风
    2020-11-21 18:02

    ++i is faster than i++ because it doesn't return an old copy of the value.

    It's also more intuitive:

    x = i++;  // x contains the old value of i
    y = ++i;  // y contains the new value of i 
    

    This C example prints "02" instead of the "12" you might expect:

    #include 
    
    int main(){
        int a = 0;
        printf("%d", a++);
        printf("%d", ++a);
        return 0;
    }
    

    Same for C++:

    #include 
    using namespace std;
    
    int main(){
        int a = 0;
        cout << a++;
        cout << ++a;
        return 0;
    }
    

提交回复
热议问题