Non-global variable constants from the header file into a function

I'm trying to work on a project, where the main program calls on a function to compute something, but the constants of the function are declared in the header file. I can get it to work using the constants as global variables, but they are not allowed to be used. I tried looking it up, but I couldn't find anything that helped.

Would putting static at the beginning prevent it from being considered "global?"
Last edited on
If you are using a constant, there are a couple of ways of doing this. If its local to a function, having a static variable in the function is the easiest way:
1
2
3
4
5
6
7
8
// myheader.h
void myfunc() {
    const int numPeople = 10000;
    // or even
    static const int numPeople = 10000;

    // ...
}


Otherwise, a constexpr (if possible) variable would be helpful:
1
2
3
4
5
6
// myheader.h
static constexpr int numPeople = 10000;

void myfunc() {
    // ...
}


If all else fails, you could use a macro, but they are commonly regarded as being at least as bad as global variables.

In answer to your question, yes, declaring it as static will stop it from being a global variable. It will instead by initialized separately in each file including the header, and changes in one file will not be reflected in a different one.

Inside a function, it works differently - it will be instantiated once for the function, and sort of acts like a global variable, except of course it isn't global (only accessible inside that function). constexpr works differently as well - think of it as working a bit like a macro, though without a number of the downsides inherent in macros.
Last edited on
Topic archived. No new replies allowed.