DEV Community

Dobby33
Dobby33

Posted on

Answer: How can I add a static assert to check if a variable is static?

You can use following trick:

#define ASSERT_LOCAL_STATIC(v) static void *p_ ## v = &v

void fn()
{
    int nonstatic_var = 0;
    static int static_var = 0;

    ASSERT_LOCAL_STATIC(static_var);
    ASSERT_LOCAL_STATIC(nonstatic_var);
}

GCC issues an error "initializer element is not constant" for non-static variables.

Top comments (0)