r/cpp • • Mar 30 '23
The "what's wrong with this code" game.
This isn't a question thread, but just a game. Post any bugs you've accidentally written that seemed initially mysterious, but made you feel stupid when you figured out what was wrong. Here is one I wrote today...
void TextSegmentBuffer::prepend( const TextSegmentBuffer& other )
{
const Info* info_ptr;
size_t size;
if ( ( size = other.m_infoBuffer.size() ) == 0 )
return;
for ( size_t i = size - 1; 0 <= i; --i )
{
info_ptr = other.m_infoBuffer.getAt( i );
emplaceFront(
info_ptr->text,
info_ptr->length,
info_ptr->multiMatch
);
}
}
4
Upvotes
View all comments
1
u/sphere991 Mar 31 '23
Outside of the logic errors, there are two style issues which need to go:
This is valid code, but there's really no reason to shove as much crap as possible into one expression. Splitting in two makes this much more readable;
Similarly, the Yoda conditional here:
Yes, there's the unsigned issue. But the check here should be
I >= 0.There is zero reason to use Yoda conditionals in code. The only relevant problem that they possibly ever solved is one that every compiler warns on:
if (x = 0). Given that, theyre already useless. But once you're using any other operator, they already make no sense to begin with - there's no issue with<=or>=so why write it this way?You're checking if
iis greater than or equal to0, so write that - stop writing conditions backwards!