Is there any case where you must use ++var? [closed]
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.
精彩评论