2

It is not duplicate to the above question as statics differences are not covered and the answers have errors.

This is a basic break-down question about memory organization within a process, and more specifically, default array values.

In a code below:
arr1 is allocated statically in a memory block near machine instructions and at some point default-initialized to 0
arr2 is supposed to be allocated on a stack when function frame is created, it is never default-initialized
arr3 is same as arr1 [?]
arr4 is same as arr2 [?]
arr5 ... now my main question besides the above two is how does the static variable inside a class differs from a static variable inside a function? I cannot access uninitialized arr5 element. In which cases I can?

int arr1[5];    

void func() {   
    int arr2[5];        printf("%d\n", arr2[0]);          // [2]
    static int arr3[5]; printf("%d\n", arr3[0]);          // [3]
}

class MyClass {
public:
    int arr4[5];
    static int arr5[5];
};

int main() 
{   
    printf("%d\n", arr1[0]);                // [1]

    func();

    MyClass obj;
    printf("%d\n", obj.arr4[0]);            // [4]
    //printf("%d\n", obj.arr5[0]);          // [5]


    std::cin.get();
}

Output:

0
-858993460
0
-858993460
user2376997
  • 501
  • 6
  • 22
  • Possible duplicate of [Uninitialized variable behaviour in C++](https://stackoverflow.com/questions/30172416/uninitialized-variable-behaviour-in-c) – L. F. Sep 27 '19 at 08:43

2 Answers2

3

According to this article arr5 is declared but not defined.

Add

int MyClass::arr5[5];

after declaration of class MyClass. Than you can get obj.arr5[0]

class MyClass {
public:
    int arr4[5];
    static int arr5[5];
};

int MyClass::arr5[5];
0

arr1 scope is global and exists until the end of the program. arr2 scope is local and it will be created and destroyed every time when a function will be called.

arr3 scope is local. Local static variables are created and initialized the first time they are used, not at program startup and will be destroyed when the program exists. arr1 and arr2 are not the same in terms of scope and initialization time. arr1 scope is global arr3 local(function scope). arr1 will be initialized when the program starts arr3 when the function will be called.

arr4 is a MyClass member it will be created/destroyed every time when you create/destroy MyClass object. It can be accessed only through MyClass object. So arr4 and arr2 are not the same. arr5 is a static class member. It is not accosted with MyClass object. You can use it without creating MyClass object. You can access it directly with the following way MyClass::arr5.