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?

7
  • 2
    You invoked undefined behavior. Determining the reason for this specific result will require detailed information of your environment. Commented Aug 23, 2020 at 15:03
  • 3
    Why do you assume n would be zero? Commented Aug 23, 2020 at 15:04
  • @MikeCAT trying to run code on hackerrank platform. hackerrank.com/challenges/simple-array-sum/problem Commented Aug 23, 2020 at 15:06
  • 1
    Even though some compilers allow int arr[n]={};, it's not valid in the standard C++ as the length must be known at compile-time. You should be using std::vector instead. Commented Aug 23, 2020 at 15:06
  • 2
    @Kathapatel You got lucky. n is uninitialized and could have any other value, and reading from it causes undefined behavior. Commented Aug 23, 2020 at 15:07

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.