If i++ adds 1 and returns the resulting value, would i+1 do the same? Can I also do i+2 etc? I try to run the following example from The Break keyword section with i+1 instead of i++, but it freezes.
You can, but not quite in that format. When
i++ is written it’s carrying out a very specific operation. Take
i, add 1, and then save this back to
i. However just writing
i+1 is just that, calculate
i+1. It’s never saved anywhere. Therefore the equivalent would be instead to do
i += 1 as this would add 1 to
i and then save it back to the variable. This can then be scaled to
i += 2,
i += 10, whatever increment you would like. Just be sure when doing this to understand what your increment is doing, sometimes it can be better to just use
i as a counter, and do any extra scaling as part of the loop eg:
But inherently there’s nothing wrong with using the
i += n format.
Great, thank you for your help!