سؤال

So I made an uninitialized array in C++ and tried printing the last element to see what the output would be. Every element in an uninitialized array should have the value of 0 (right?), but the output I got was something else. This is what the main function looked like:

int main() {
    int i[5];
    cout << i[4] << '\n';
}

Running this outputs 1606416656 (same number every time) with a line break. However, changing '\n' to endl changes the output to 0 with a line break.

Why is that?

Also, trying to print i[3] instead of i[4] correctly outputs 0 even with '\n'. Why?

I did some research and read somewhere that '\n' doesn't "flush the buffer" while endl does. What does this "flushing the stream" actually mean, and is this what's affecting the output?

هل كانت مفيدة؟

المحلول 2

Your assumption that an newly created array on the stack is initialized with zero does not hold. Therefore your output is random. Changing the program reorders the memory layout and so you see different results.

int main() {
    int i[5];
    for (int k = 0; k < 5; ++k)
        i[k] = 0;
    cout << i[4] << '\n';
}

should give you always the expected result regardless of using '\n' or endl

نصائح أخرى

Every element in an uninitialized array should have the value of 0 (right?)

No, they have an indeterminate value. Using the values gives undefined behaviour, which is why you get unpredictable output.

What does this "flushing the stream" actually mean, and is this what's affecting the output?

When you write to the stream, the output is stored in a memory buffer, and not necessarily sent to the final destination (the console, or a file, or whatever) straight away; this can give a large performance benefit, but can also mean that you don't see the final output when you want to. Flushing the stream pushes the data you've written to the final destination.

Your array remains uninitalized. Whatever value you get is coincidental. std::endl puts newline character and flushes the output stream buffer. That is the difference of std::endl manipulator and printing just a newline character.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top