Problem
I found out that I can increase the value of a variable inside an if statement like so:
int limit = 100;
int nrCopies = 2;
int maxValue = 100;
for(int i = 0; i < limit; ++i)
{
if((nTotal += (nrCopies)) > maxValue)
break;
}
This works, and I became acostumed to do this, but I want to know if it is a good practice to do so, since I don’t want to get bad habits unnecessarily
Solution
I would say this is quite questionable.
Imagine you never saw this code before, and are trying to understand it, would this make it easier to understand or harder? I say harder.
I agree with @GeorgeBarwood answer, full stop.
Next note @ Peilonrayz comment …we don’t have enough context
If the contex or intent is to emphasize “Increment until reaching the max value”, or better: “make this many copies”, then use a while
loop.
int total = 0;
while (total <= maxValue) {
total += nCopies;
}