1
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ This is a generic best practice question. This is not particularly helpful as a Python programmer would say no, but a JavaScript programmer would say yes. Ultimately we don't have enough context to know if this is good or not. \$\endgroup\$
    – Peilonrayz
    Commented Jun 29, 2020 at 17:26

2 Answers 2

3
\$\begingroup\$

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.

\$\endgroup\$
0
0
\$\begingroup\$

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;
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.