Home > Software engineering >  Does a const variable behave like a static variable when defined in a C function?
Does a const variable behave like a static variable when defined in a C function?

Time:12-23

I have a small query. In C , is it legal and/or sensible to define a const integer within a function, the value of which depends on the input arguments of the function? And if it is, does the value stay constant within the function and changes with different calls to the function with different arguments, or does it stay constant over the scope of the entire program like a static variable?

Here's a quick example of what i mean in code.

void testMyVar(int x, int y){
   const int z = x/y;
   //use z for whatever computation
}

Thanks for your help in advance!

CodePudding user response:

A variable declared as const cannot be modified once it is initialized.

In this case, when the function is entered z is initialized with the value of x/y and will keep that value for the duration of the function. And each time the function is called, z will be initialized with whatever values for x and y were passed.

There is no behavior related to static since the variable was not declared static.

CodePudding user response:

Realize that z is "destroyed" once it goes out of scope since it is NOT static. This is true if z is at function scope or nested 3 levels deep in an if/for/if

static int z = 42;  // I will label this z0

void testMyVar(int x, int y) {
    const int z = x/y;  // I will label this z1; this z is different than the static z above (z0)
    if (z > 10) {  // tests z1, not z0
        int z = x;  // non-const z; I will label this z2, which is different than z1 and z0
        z  ;  // C   uses inner-most scoped z (so here, it's z2), so this is good (non-const)
        for (int i = 0; i < z; i  ) {
            int z = i / 2;  // I will label this z3, it gets re-evaluated every time through the for loop
            z = z * z;  // all 3 z refererences here is z3
            cout << z << endl;  // dumps z3
            cout << ::z << endl;  // dumps z0 note the global scoping operator ::
            }  // z3 gets "destroyed"
        }  // z2 gets "destroyed"
    }  // z1 gets "destroyed

C grammar does not provide mechanisms for specifying scope of named variables at different code scopes, just at global, class/struct, and namespaces. So you cannot specifically utilize the top level const int z (what I labeled z1) within the code nesting levels where deeper z's z2/z3 are defined. Note that I CAN reference the "global" scoped static z ::z at the z3 level by utilizing the global scope operator ::

  • Related