+ 1

Why it is giving infinity loop when i write i=i++ ? but when i write i = ++i . It work well .

Is it right to use ++i ? Why i++ giving infinity loop ? https://code.sololearn.com/c4JVhs76s2pC/?ref=app

27th Feb 2022, 12:46 PM
Abhay mishra
Abhay mishra - avatar
3 Answers
+ 2
G'day Abhay mishra you didn't say that the infinite loop is at i=0.... That makes much more sense. The common use for var++ is to add 1 to the variable that is the increment counter for the loop. var++ is practically the same as var=var+1 The difference is that var++ increases according to the compilers order of code execution, (which will be unpredictable between different systems or undefined) ++var is also equivalent to var=var+1 The order of execution of ++var is much more predictable, it always increments before being used in that line of code. TLDR: you have confused the system with postfix as well as definition in the same line of code. Change 👎i=i++; to be 👍i++;
27th Feb 2022, 11:39 PM
HungryTradie - avatar
+ 4
Because ++i is known as prefix while i++ is postfix. See here https://www.sololearn.com/learn/C/2917/?ref=app
27th Feb 2022, 12:52 PM
Simba - avatar
+ 3
Look at the warning when you use ++i. From Wikipedia: "An often-cited example is the C expression i=i++, which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior." More: https://en.m.wikipedia.org/wiki/Sequence_point
27th Feb 2022, 1:00 PM
devanille - avatar