C: What is the difference between ++i and i++?

前端 未结 21 2066
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 06:04

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

21条回答
  •  执笔经年
    2020-11-21 06:25

    The difference can be understood by this simple C++ code below:

    int i, j, k, l;
    i = 1; //initialize int i with 1
    j = i+1; //add 1 with i and set that as the value of j. i is still 1
    k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
    l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
    cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
    return 0;
    

提交回复
热议问题