+ 1
Why do we need post increments and decrements? how are they useful?
4 Respuestas
+ 7
increments and decrements are most useful when performing a loop. For example, you want to loop a monster attack for 4times.
int x = 0
while ( x<4 )
{
//code of monster attacking
x++; /* or ++x; will work too, since the 'x' is going to get increased anyway*/
};
This makes the increments helpful as they allow loops to happen and prevent infinite loops. You can do the same for decrement too! For example :
int x = 4
while (x>0)
{
//Monster attack
x--; /*again, --x works too since at the end of the while code, x is definately going to be decreased before it loops again*/
};
+ 1
Increments and decrements are performing faster than substraction or addition operations and making code easier to understand.
+ 1
You can use a variable and then increment/decrement it in just one instruction (post)
You can increment/decrement a variable and then use just one instruction (post)
example:
int x = 5;
//print 5
Console.WriteLine(x++);
//print 6
Console.WriteLine(++x);
0
they save you some lines of code