Useless Increment
ID |
php.no_useless_increment |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
dead-code, reliability, suspicious-assignment |
Description
A postfix ++ or -- whose result is thrown away: the variable is updated and the update is then
lost, so the statement does not do what it appears to do.
Postfix yields the value the variable held before the operator applied. Returning it from a function whose local dies with the call, or assigning it back over the variable it just updated, discards the increment entirely.
Rationale
public function next(int $seq): int
{
return $seq++; // returns the OLD value; $seq is gone when the call ends
}
$seq = $seq++; // evaluates to the old value, writes it back: a no-op
The first function looks like a counter and behaves like the identity. The second statement reads as an increment and changes nothing at all.
Remediation
public function next(int $seq): int
{
return $seq + 1; // or: return ++$seq;
}
$seq++; // the increment on its own
Only two shapes are reported, both unambiguous: the postfix as the whole returned expression, and the postfix assigned back to its own target. These stay silent, because the update survives:
public function next(int &$seq): int { return $seq++; } // the caller sees the new value
public function nextId(): int { return $this->next++; } // the property keeps it
public function next(): int { static $n = 0; return $n++; }
public function next(int $seq): int { return ++$seq; } // prefix returns the new value
$other = $seq++; // a distinct target
return $seq++ + 1; // the value is consumed
$seq++; // the normal idiom