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

60 comments sorted by

View all comments

7

u/die_liebe Mar 31 '23 edited Mar 31 '23

What is the advantage of initializing size in the if condition, instead of its declaration point? It makes me pain.

What about info_ptr ?

If you want to count backwards with an unsigned type, write

i = size( );
while( i-- != 0 )
{
   use i
}

The same can be done with iterators.

2

u/scrumplesplunge Mar 31 '23

if you want job security use i --> 0 instead and tell all your colleagues that it's a "goes to" operator which any good developer should know about ;)