do-while | SoloLearn: Learn to code for FREE!



Hi! Why does the increment a ++ and ++ a of the example below make no difference in the program? int a = 0; do { Console.WriteLine(a); a++; } while(a < 5); /* Outputs 0 1 2 3 4 */ Thank you!

6/21/2017 9:52:21 PM

Cidinei Magalhães Sargaço

9 Answers

New Answer


because they both do the same thing in this context


Because it's in its own statement. a++ first uses then increments. So, look at the statement: a++. First use. Ok, well we're not really using it for anything except incrementing it anyway. Increment, ok now a = a +1. Now look at ++a. First increment. Ok, now a = a +1; Now use. Ok, well we aren't really using it. Just assigning a. I don't get the source of your confusion. Did you mean to ask: Console.WriteLine(++a); Or Console.WriteLine(a++); ?? Because that will surely give different results, as the ++a one will increment first. So the first result would be 1.


@Limitless. does prefix/postfix work like that in c#. I was under the impression that var++ increments after the statement/expression is evaluated. Not wait until next time it is encountered.


thought so, i wasnt sure about in c# either thus the question. I am sure that is how it works in c++ though.


So try putting the a++ and ++a in your Console.WriteLine() You'll get 1..5 and 0..4 Now why is this? If you look at the rules of the ++ function you'll know that the a variable will increase immediately when it's ++a and when it's a++ it will only increase once it's used again. Now the reason why it didn't matter in your code was because when the a variable got to While(a < 5) the value would the same in both cases. if you wanted it to be different I would suggest something like While(a++ < 5) That will make it loop one more time ;)


here in this context a++; is terminated there.. but if it would be have been like considering int a=5; b=a++; // output will be b=5, and a=6 and one more expression c=++a; // Output will be c=6 and now a=7


"i++ means 'tell me the value of i, then increment' ++i means 'increment i, then tell me the value'" Safe to say you're right


Now I understand. What was making me confused was the line "console.WriteLine (a);" But changing this line to "console.WriteLine (a ++)" or "console.WriteLine (++ a)" is easier to understand. Here's how the two exits are: int a = 0; do { Console.WriteLine(++a); } while(a < 5); /* Outputs 1 2 3 4 5 */ int a = 0; do { Console.WriteLine(a++); } while(a < 5); /* Outputs 0 1 2 3 4 */ The line "console.WriteLine (a)" forced the program to start "a" always at 0. Anyway, thank you for the help.


Ok maybe it's changed after it's been used. Not sure about that