开发者

Can someone explain the ++ operator? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C#: what is the difference between i++ and ++i?

I see this operator (++) very often. I know what it d开发者_Python百科oes ultimately, but it seems like there's some rules I don't understand. For example, it seems to matter if you put it before or after the variable you're using it on. Can someone explain this?


The statement

x++;

is exactly equivalent to

x = x + 1;

except that x is evaluated only once (which makes a difference if it is an expression involving property getters).

The difference between the following two:

DoSomething(x++);   // notice x first, then ++
DoSomething(++x);   // notice ++ first, then x

Is that in the first one, the method DoSomething will see the previous value of x before it was incremented. In the second one, it will see the new (incremented) value.

For more information, see C# Operators on MSDN.

It is possible to declare a custom ++ operator for your own classes, in which case the operator can do something different. If you want to define your own ++ operator, see Operator Overloading Tutorial on MSDN.


http://msdn.microsoft.com/en-us/library/36x43w8w(v=VS.80).aspx

The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand:

The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.

The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.


If you put the ++ operator before the variable, it is incremented first. If you put the ++ operator after the variable, it is incremented after.

For example(C#):

int x = 0;
Console.WriteLine("x is {0}", x++); // Prints x is 0

int y = 0;
Console.WriteLine("y is {0}", ++y); // Prints y is 1

Hope this cleared it up.


well if you put it like

variable++

It first uses the variable and the increments it (+1) On the otherhand if you

++variable

It first increments the variable and then uses it


Another way to see it... here are two functions that do the same as prefix/postfix ++. This illustrates that prefix is, in theory, faster, because no temporary variable is needed to store the "previous" value:

// same as x ++;
int PostfixIncrement(ref int x)
{
    int y = x;
    x = x + 1;
    return y;
}

// same as ++ x;
int PrefixIncrement(ref int x)
{
    x = x + 1;
    return x;
}


If you put the ++ operator before the variable, it is incremented first. If you put the ++ operator after the variable, it is incremented after.

For example(C#):

int x = 0; Console.WriteLine("x is {0}", x++); // Prints x is 0

int y = 0; Console.WriteLine("y is {0}", ++y); // Prints y is 1

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜