Advertisement
ivandrofly

Pre vs Post Incrementing

Feb 23rd, 2015
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.65 KB | None | 0 0
  1. C#:
  2. Part #1:
  3. string[] items = {"a","b","c","d"};
  4. int i = 0;
  5. foreach (string item in items)
  6. {
  7.     Console.WriteLine(++i);
  8. }
  9. Console.WriteLine("");
  10.  
  11. i = 0;
  12. foreach (string item in items)
  13. {
  14.     Console.WriteLine(i++);
  15. }
  16. Output:
  17.  
  18. 1
  19. 2
  20. 3
  21. 4
  22.  
  23. 0
  24. 1
  25. 2
  26. 3
  27.  
  28. Part #2:
  29. Pre-increment ++i increments the value of i and evaluates to the new incremented value.
  30.  
  31. int i = 3;
  32. int preIncrementResult = ++i;
  33. Assert( preIncrementResult == 4 );
  34. Assert( i == 4 );
  35. Post-increment i++ increments the value of i and evaluates to the original non-incremented value.
  36.  
  37. int i = 3;
  38. int postIncrementResult = i++;
  39. Assert( postIncrementtResult == 3 );
  40. Assert( i == 4 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement