0

in the following "while" code:

int digit = 0;
        while(++digit < 10) 
            Console.WriteLine(digit);

This prints out 1,2,3,4,5,6,7,8,9 This makes sense to me, since it should stop at 10, since 10<10 is false.

However, when we switch from pre-increment to post-increment for digit:

int digit = 0;
        while(digit++ < 10) 
            Console.WriteLine(digit);

Then it prints out 1,2,3,4,5,6,7,8,9,10

I don't understand why it performs Console.WriteLine and prints out 10 in this case, since 10<10 is false.

Can anyone please explain?

Thanks

  • https://stackoverflow.com/questions/8573190/pre-post-increment-in-c-sharp - already answered here – shat90 Aug 06 '20 at 02:25
  • I guess the question already contains the answer since you are aware of both prefix and postfix operators. In this case, increment will be executed with `digit++` **after the condition get evaluated** and hence the last output was 10 while its condition remains true (i.e. 9 < 10). – Zephyr Aug 06 '20 at 02:25
  • And this is a good reason to avoid performing assignment and comparison in the same statement. Had that loop been written as `for(int i = 0; i < 10; i++)` this wouldn't have happened, your confusion wouldn't have happened, having to ask on SO wouldn't have happened and "having to remember one more thing to prevent an off by one bug" wouldn't have happened. Avoid this code golf pattern wherever you can, for reasons of clarity/code self documentability and remember "just because you can, doesn't mean you should" ;) – Caius Jard Aug 06 '20 at 05:28
  • Does this answer your question? [Pre- & Post Increment in C#](https://stackoverflow.com/questions/8573190/pre-post-increment-in-c-sharp) – Peter Csala Aug 06 '20 at 06:45
  • Yes, especially Zephyr's comment, which makes the most sense to me. – Julius Dahne Aug 07 '20 at 02:41

1 Answers1

0

In the second block of code, when digit is 9, the code digit++ is evaluated and it returns 9 but it sets the value of digit to 10. Then on the Console.WriteLine(digit); it simply prints the 10.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172