开发者

Is there any case where you must use ++var? [closed]

开发者 https://www.devze.com 2023-03-08 02:05 出处:网络
开发者_Python百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current for
开发者_Python百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

The question is whether there is a situation where you can not use var++ and must use ++var (or the other way around).

That is, as far as I know, the only reason to use ++var over var++ (or the other way around) is to save space.

The question is, can we just have only the var++ abillity and not lose anything in the language's power?


You have to use ++var if you're using the expression within a bigger expression, and you definitely want the value of the expression to be the incremented one. For example, in C#:

int foo = 0;
foreach (var x in someCollection)
{
    Console.WriteLine("{0}: {1}", x, ++foo);
}

Of course you could change this to use foo++ in a separate statement, but that isn't always feasible:

int foo = 0;
Expression<Func<int>> expression = () => ++foo;

That will return 1 the first time you call it, and you can't convert statement lambdas to expression trees.

0

精彩评论

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

关注公众号