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

后端 未结 6 2116
暗喜
暗喜 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

    If you have:

    int i = 10;
    int x = ++i;
    

    then x will be 11.

    But if you have:

    int i = 10;
    int x = i++;
    

    then x will be 10.

    Note as Eric points out, the increment occurs at the same time in both cases, but it's what value is given as the result that differs (thanks Eric!).

    Generally, I like to use ++i unless there's a good reason not to. For example, when writing a loop, I like to use:

    for (int i = 0; i < 10; ++i) {
    }
    

    Or, if I just need to increment a variable, I like to use:

    ++x;
    

    Normally, one way or the other doesn't have much significance and comes down to coding style, but if you are using the operators inside other assignments (like in my original examples), it's important to be aware of potential side effects.

提交回复
热议问题