0
What's the difference between postfix and prefix in C#?
I didn't quite understand what the difference between a prefix (f.e: ++i) and postfix (f.e i++) is. Can someone please in detail explain what the differences are, and how it would affect a value?
5 Respuestas
+ 15
• Increment and Decrement Operators
The increment and decrement operators (++, --) increment and decrement numeric types by 1. The operator can either precede or follow the variable, depending on whether you want the variable to be updated 'before' or 'after' the expression is evaluated.
For example:
int x = 0;
Console.WriteLine(x++); // Outputs 0;
x is now 1
Console.WriteLine(++x); // Outputs 2;
x is now 2
Console.WriteLine(--x); // Outputs 1;
x is now 1
D_Stark Thank you!😊
• https://code.sololearn.com/cCEWmvfjC837/?ref=app
+ 16
Ivaylo Valchev
[ ++i and i++ both add 1 to i ]
However, ++i returns the new value, and
i++ returns the old value.
Likewise for decrement, --i and i--, which subtracts 1.
An easy way to remember how these operators behave involves these two rules:
• If the operator appears 'before' the operand, the operation will occur 'before' the expression has been evaluated.
• If the operator appears 'after' the operand, the operation will occur 'after' the expression has already been evaluated.
+ 13
Ivaylo Valchev
You should check out the comments in the lesson — https://www.sololearn.com/learn/CSharp/2590/
You will find excellent explanation!👍
+ 6
Danijel Ivanović explains this very well please see.
https://code.sololearn.com/c40cT81cpKl2/?ref=app
+ 1
D_Stark Thanks, this was greatly explained :)