In C# what is the difference between myInt++ and ++myInt?

后端 未结 11 1815
我寻月下人不归
我寻月下人不归 2020-12-06 03:11

I\'m having a hard time understanding what the difference is between incrementing a variable in C# this way:

myInt++;

and

         


        
相关标签:
11条回答
  • 2020-12-06 03:34

    The pre-fix operator ++myInt is a way of reducing lines: increment the variable before passing it to someplace else. It's also a nice way to reduce readability, since it's uncommon.

    MyMethod(++myInt); 
    

    vs.

    myInt++; 
    MyMethod(myInt);
    

    To me the second is a lot easier to read.

    0 讨论(0)
  • 2020-12-06 03:37

    myInt++ (4 CPU instructions)

    LOAD AX, #myInt // From myInt memory to a CPU register
    COPY AX, BX
    INCREMENT BX
    STORE BX, #myInt
    // Use AX register for the value
    

    ++myInt (3 CPU instructions)

    LOAD AX, #myInt // From myInt memory to a CPU register
    INCREMENT AX
    STORE AX, #myInt
    // Use AX register for the value
    
    0 讨论(0)
  • 2020-12-06 03:42

    ++myInt will add one to myInt before executing the line in question, myInt++ will do it afterward.

    Examples:

    int myInt;
    
    myInt = 1;
    someFunction(++myInt); // Sends 2 as the parameter
    
    myInt = 1;
    someFunction(myInt++); // Sends 1 as the parameter
    
    0 讨论(0)
  • 2020-12-06 03:43

    It is a difference if you are doing

    int x = 7;
    int x2 = x++;
    
    => x2 is 7 and x is 8
    

    but when doing

    int x = 7;
    int x2 = ++x;
    
    => x2 is 8 and x is 8
    
    0 讨论(0)
  • 2020-12-06 03:43

    I think it is simplest to understand in terms of the order of evaluation and modification.

    • The postfix operator (x++) evaluates first and modifies last.
    • The prefix operator (++x) modifies first and evaluates last.

    (the order of operations is evident in the typed order of the operator and the variable)

    I.e. when used in an expression, the postfix operator evaluates and uses the variable's current value in the expression (a return statement or method call) before applying the operator. With the prefix operator it is the other way around.

    0 讨论(0)
提交回复
热议问题