How to make a local variable in C (or C ++) global?

1

Can I make a local variable turn into global, even though it's inside a function? In C language or even C ++ if it does not exist in C. I have already seen something of the type in Java, but I do not know exactly how it works.

    
asked by anonymous 19.06.2016 / 18:50

2 answers

1

Do as everyone said, or even better, declare outside the scope of the function and as static.

static int variavel=0;

void X()
{
      variavel++;
}
int main()
{
     cout << variavel; 
     variavel ++;
     cout << variavel;
     X();
     cout << variavel;
     return 0;
}
    
15.03.2017 / 07:53
0

The only way (as far as I know) that you have a global variable in C is to declare it out of any function, just like any other global variable.

I imagine what you're wanting is to declare a local variable with the behavior of a global variable, with scope limitations. For this use the word static .

void funcao(){
    static int k = 0;
    k++;
    printf("%d\n", k);
}

When calling the function 3 times, it will print:

1
2
3

The explanation for this is due to the fact that by declaring a local variable as static, it will be stored in another memory location. Whenever there is a function call, the so-called call stack is generated, a space is reserved for storing local variable values, and when the function exits the region is released. When using static, the variable is allocated elsewhere.

There is an interesting read on the function call stack, if you are interested: BufferOverflow

I recommend: Static: The Multipurpose Keyword

    
19.06.2016 / 22:03