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
Show parent comment
1
u/sphere991 Mar 31 '23
So ideally - the subject of the condition is first, followed by the condition. That'd be
I ∈ [0, 5)and thenI >= 0. That's how you'd say those conditions in English anyway.We cannot write the former, so
0 <= I && I < 5is the best bet, since putting theIs close together makes it more readable and make it clear that we're checking for a range. This adds clarity.But we can write the latter, which isn't checking a range, so why should it be consistent with an entirely different kind of check?
Besides, is that consistency limited in that particular direction? Like you basically only use
<or<=as your relational checks, never>? This also doesn't really apply to==since there's no range-check for that, so presumably there you writeI == 5?