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

后端 未结 6 2059
暗喜
暗喜 2020-11-21 23:13

I\'ve seen them both being used in numerous pieces of C# code, and I\'d like to know when to use i++ or ++i (i being a number variable

6条回答
  •  無奈伤痛
    2020-11-21 23:22

    The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:

    int x = 0;   //x is 0
    int y = ++x; //x is 1 and y is 1
    

    If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:

    int x = 0;   //x is 0
    int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
    

    I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:

    while (x < 5)  //evaluates conditional statement
    {
        //some code
        ++x;       //increments x
    }
    

    or

    while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
    {
        //some code
    }
    

    You can also do this while indexing arrays and such:

    int i = 0;
    int[] MyArray = new int[2];
    MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
    MyArray[i] = 5678;   //sets array at index 1 to '5678'
    int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
    

    Etc, etc...

提交回复
热议问题