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

Show parent comments

2

u/Possibility_Antique Mar 31 '23

I see the i that should be a j, but the purist in me says you should flatten your array and not make it an array of arrays. It's faster and less error prone, and you wouldn't have had this problem to begin with.

2

u/elperroborrachotoo Mar 31 '23

Who says the internal representation isn't flattened?

1

u/TheThiefMaster C++latest fanatic (and game dev) Mar 31 '23

As long as the inner array is either a C or std array, and the outer is any consecutive container (C array, std array, std vector...) it will be fully consecutive in memory and the optimiser may even flatten the loops into a single loop.

Though the flattening of the loops into a single loop is less important than you might think, because a couple of extra instructions will easily fit inside the delay of the consecutive memory accesses even coming from cache