Brain Teaser: Streaming An Enumeration In C++

Streaming an enumeratoin in C++, what could be easier? Can you spot the bug in the following code?

typedef enum {
    SEASON_UNDEF,
    SEASON_SUMMER,
    SEASON_AUTUMN,
    SEASON_WINTER,
    SEASON_SPRING,
    SEASON_NUM_TYPES,
} SEASON;
 
 
std::ostream& operator<<(std::ostream& rOs, 
                         const SEASON & rRhs)
{
    switch (rRhs)
    {
    case SEASON_UNDEF:
        rOs << "SEASON_UNDEF";
        break;
 
    case SEASON_SUMMER:
        rOs << "SEASON_SUMMER";
        break;
 
    case SEASON_AUTUMN:
        rOs << "SEASON_AUTUMN";
        break;
 
    case SEASON_WINTER:
        rOs << "SEASON_WINTER";
        break;
 
    case SEASON_SPRING:
        rOs << "SEASON_SPRING";
        break;
 
    default:
        rOs << "Unknown SEASON: " << rRhs;
        break;
    }
 
    return rOs;
}

Scroll down for the answer….

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Nearly there… 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

You’ve got it, its the default case. This makes a recusive call which will never terminate. Now how much stack space do I have….

rOs << "Unknown SEASON: " << rRhs; // Recusive call!

Leave a Reply

Your email address will not be published. Required fields are marked *