0

Here I am declaring array length before taking input for n. At the time of array declaration n=0.

#include <iostream>
using namespace std;

int main() {
    int n;
    int sum=0;
    int arr[n]={};
    cin >> n;

    for(int i=0;i<n;i++) {
        cin >> arr[i];
        cout << arr[i];
    }
    return 0;
}

for below input 6 1 2 3 4 5 6

I am getting this output 1234.

Can someone please explain the reason?

Katha patel
  • 121
  • 10

1 Answers1

2

Here I am declaring array length before taking input for n.

Yes, but that's no valid C++. It's a compiler specific extension. See Why aren't variable-length arrays part of the C++ standard?

At the time of array declaration n=0.

That's wrong. n has not been initialized, so it contains garbage data (which could be 0). Reading n invokes undefined behaviour.

Even if n would be 0, the loop would access the array out of bounds and undefined behaviour is invoked again.

Discussing the output of a program that invokes undefined behaviour is pointless - anything might happen. The only reasonbale thing is to avoid UB. Some good practices to do this:

  • Always initialize variables to a reasonable value
  • use std::vector instead of plain arrays/VLAs.
Lukas-T
  • 11,133
  • 3
  • 20
  • 30