开发者

what does x-- or x++ do here?

it is a silly Q for most of u - i know - but i one of the beginner here, a开发者_JAVA技巧nd I can not understand why the output in here are 12 what does this (x--) do to the result ?

int x, y;
x = 7;
x-- ;
y = x * 2;
x = 3;


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.


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


-- 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).


x++ increments x after x being evaluated. ++x increments x before x being evaluated.

 int x = 0;
 print(++x); // prints 1
 print(x); // prints 1

 int y = 0;
 print(y++); // prints 0
 print(y); // prints 1

The same goes for --


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)


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜