0

When I ran the following code:

#include <iostream>

using namespace std;

int main() {
    int arrayTest[8];

    for (int i = 0; i < 8; i++) {
        cout << arrayTest[i] << endl;
    }

    return 0;
}

It outputted:

0
0
0
-245235546
-143858606
117716240
1

But when I ran it again, it outputted:

0
0
0
-594607916
44357026
177595664
1

I'm wondering where it got numbers such as -245235546, 44357026... from, why the first 3 numbers are 0 and the last is 1, and why the output changes every time I run the code.

I apologize in advance if this is a simple question, I am a beginner to c++

realhuman
  • 137
  • 1
  • 8
  • 3
    It's simply _undefined behavior_ to access uninitialized variables. Futile to ask why it behaves as it does. – πάντα ῥεῖ Nov 27 '22 at 07:52
  • 1
    See [What happens when I print an uninitialized variable in C++?](https://stackoverflow.com/questions/30180417/what-happens-when-i-print-an-uninitialized-variable-in-c) and [Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?](https://stackoverflow.com/questions/49032551/why-is-the-phrase-undefined-behavior-means-the-compiler-can-do-anything-it-wan) – Jason Nov 27 '22 at 07:54
  • When you initialize an array inside the main function, the compiler allocates memory from the physical memory. The allocated memory may contain some garbage values (Used in some other program and then freed the memory). But if you initialize the array globally, the compiler will allocate memory and initialize with '0'. So the garbage value (used in some other program) gets overwritten. – sat Nov 27 '22 at 07:57
  • I Will try to make my comment clear.. first you should know what is the c++ not clearing memory for new variables it just allocate , in the first of function you declare an array of int all what compiler do is reserve `8*sizeof(int)` bytes in memory (`stack` segment) the the compiler only assign memory for local variable the memory of course has old values . so when you read array element the compiler read the exactly address which contains old values or even part of value (object). – Mustapha Elzehary Nov 27 '22 at 08:00

0 Answers0