0

I was wondering what would happen if we kinda "redefine"(that's not a good term for what is happening) a static variable.

#include <iostream>
void insert(int k) {
    static int jo = k;
    std::cout << jo << std::endl;
}
int main()
{   
    insert(1);
    insert(2);
}//output  1 and 1

I expected that the code above would have a problem, but it runs without any. At least I would expect that the 2 of insert(2) would go to some other memory location, but I couldn't find it. Although if we change it to:

#include <iostream>
int main()
{   
    static int jo = 1;
    std::cout << jo << std::endl;
    static int jo = 2;
    std::cout << jo << std::endl;
}// 'jo' redefinition; multiple initialization

We get a problem, in this case I believe that's because the two declarations potentially conflict and one precedes the other what I think don't apply to the first code of this question. What happens in the first code?

  • A local static variable is initialized when it is first elaborated (execution first hits that line) -- this happens on the first call to `insert` which initializes it to 1 and it stays at 1. – wcochran Nov 08 '21 at 19:53
  • @wcochran I agree, but the 2 I sent as argument is totally discarded ? I was expecting it being some garbage somewhere –  Nov 08 '21 at 19:58
  • 1
    Yeah -- the 2 is unused in the second call. Note that `static int jo = k;` is *not* an assignment -- it is an initialized declaration. Change so that an assignment is used and you will see it change. – wcochran Nov 08 '21 at 20:02

0 Answers0