Search code examples
c++oopstaticinitializationcppunit

CppUnit: Why does a static local variable keep its value?


I'm trying to use CppUnit to test a method that should execute some code only the first time it is called.

class CElementParseInputTests: public CppUnit::TestFixture {
private:
    CElement* element;
public:

    void setUp() {
        element = new CElement();
    }

    void tearDown() {
        delete element;
    }

    void test1() {
        unsigned int parsePosition = 0;
        CPPUNIT_ASSERT_EQUAL(false, element->parseInput("fäil", parsePosition));
    }

    void test2() {
        unsigned int parsePosition = 0;
        CPPUNIT_ASSERT_EQUAL(false, element->parseInput("pass", parsePosition));
    }

The recursive method I want to test:

bool CElement::parseInput(const std::string& input, unsigned int& parsePosition) {
    static bool checkedForNonASCII = false;
    if(!checkedForNonASCII) {
        std::cout << "this should be printed once for every test case" << std::endl;
        [...]
        checkedForNonASCII = true;
    }
    [...]
    parseInput(input, parsePosition+1)
    [...]
}

Since the object is recreated and then destroyed for every test case, I would expect that the string "this should be printed once for every test case" would be printed twice when running the tests, but it's only printed once. What have i missed?


Solution

  • That's what static local variables supposed to do.

    Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

    That means checkedForNonASCII will be initialized to false only once for the 1st call. For further calls the initialization is skipped; i.e. checkedForNonASCII won't be initialized to false again.