what does x— or x++ do here?

后端 未结 7 1168
猫巷女王i
猫巷女王i 2021-01-23 01:53

it is a silly Q for most of u - i know - but i one of the beginner here, and I can not understand why the output in here are 12 what does this (x--) do to the resu

相关标签:
7条回答
  • 2021-01-23 02:34

    x-- will decrement value of x by 1. It is a postfix decrement operator, --x is a prefix decrement operator.

    So, what's going on here?

     
    int x, y;    //initialize x and y
    x = 7;       //set x to value 7
    x--;         //x is decremented by 1, so it becomes 6
    y = x * 2;   //y becomes 6*2, therefore y becomes 12
    x = 3;       //x becomes 3

    By analogy, the ++ will increase a value by 1. It also has a prefix and postfix variant.

    0 讨论(0)
  • 2021-01-23 02:36

    -- is the 'decrement' operator. It simply means that the variable it operates on (in this case the x variable) gets is decremented by 1.

    Basically it is shorthand for :

    x = x - 1;
    

    So what the code does :

    int x,y ; # Define two variables that will hold an integer
    x=7;      # Set variable X to value 7
    x-- ;     # Decrement x by one : so x equals 7 - 1 = 6
    y= x * 2; # Multiply x by two and set the result to the y variable: 6 times 2 equals 12
    x=3;      # set x to value 3 (I do not know why this is here).
    
    0 讨论(0)
  • 2021-01-23 02:37

    Example:

    x = 7;
    y = --x; /* prefix -- */
    

    Here y = 6 (--x reduce x by 1)

    y = x--; /* postfix -- */
    

    Here y = 6 (x-- use first the value of x in the expression and then reduce x by 1)

    0 讨论(0)
  • 2021-01-23 02:42

    Just a cautionary note, sometimes the pre and post increment operators can have unexpected results

    Why does this go into an infinite loop?

    and what does:

    x[i]=i++ + 1;
    

    do

    Read here: http://www.angelikalanger.com/Articles/VSJ/SequencePoints/SequencePoints.html

    0 讨论(0)
  • 2021-01-23 02:45

    x-- subtracts/decrements the value of x by one.

    Conversley x++ adds/increments by one.

    The plus or minus signs can either be before (--x) or after (x--) the variable name, prefix and postfix. If used in a expression the prefix will return the value after operation has been performed and the postfix will return the value before operation has been performed.

    int x = 0;
    int y = 0;
    y = ++x; // y=1, x=1
    
    int x = 0;
    int y = 0;
    y = x++;// y=0, x=1
    
    0 讨论(0)
  • 2021-01-23 02:50

    x++ is essentially x = x + 1 (the same applies for ++x). x is incremented by 1.

    x-- is essentially x = x - 1 (the same applies for --x). x is decremented by 1.

    The difference is that how x++ and ++x is used in the statement/expression: In ++x, x is incremented by 1 first before being used while in x++, x is used (before incrementation) first and once it's used, it gets incremented by 1.

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