0

Hi guys i wanna to understand "static" in C plz help me

Question

18th Nov 2020, 8:42 PM
Hamdi Nahdi
Hamdi Nahdi - avatar
2 Antworten
+ 3
I wrote a little code that shows what's going on with storage class and scope. https://code.sololearn.com/cbkl13kv634r/?ref=app printAuto keep printing 1 because every time you exit the function the local variable i is destroyed and in the next call it is declared again with a value of 0. When you exit printStatic instead i continues to exist, holding its value. It's not going to be declared again. There are three functions: main, printAuto and printStatic. Each of them has a variable named i, however the name is the only thing that these variables share. They have different values and addresses. The i in the main continue to exist while the control is passed to the other functions because you never exit the main. However it cannot be accessed by the other functions because it's outside of their scope, they can't see it. The i of printStatic continue to exist when you exit the function, however it can't be accessed in the main because the main it's outside of it's scope.
19th Nov 2020, 1:40 AM
Davide
Davide - avatar
+ 2
By default C variables exist only within the block where they are declared. They are said to be of automatic storage class. By using the keyword "static" you are able to declare a variable of static storage class, i.e. a variable that exist for all the duration of the program. Even though they exist during the whole program execution, they can be accessed only within the block in which they are declared. Scope and storage class are two different things.
19th Nov 2020, 12:24 AM
Davide
Davide - avatar