iLLiadPorg
iLLiadPorg

Reputation: 21

Not trying to get random numbers for the values in my array

I am new to programming in C++. I just would like to know why this code works, giving me actual numbers:

#include <iostream>
using namespace std;

int main(){ 

    const int ARRAYSIZE = 10;
    int inc = 0;
    int arrayy[ARRAYSIZE];

    while (inc < ARRAYSIZE) {

        arrayy[inc]=inc;
        std::cout << arrayy[inc]<< endl;
        inc++;  
    }
}

But this code gives me random numbers for the values in my array:

#include <iostream>
using namespace std;

int main(){ 

    const int ARRAYSIZE = 10;
    int inc = 0;
    int arrayy[ARRAYSIZE];

    while (inc < ARRAYSIZE) {

        arrayy[inc]=inc;
        inc++;
        std::cout << arrayy[inc]<< endl;
        
    }
}

Upvotes: 1

Views: 40

Answers (2)

Alex
Alex

Reputation: 632

Values in the array are not initialized to any particular value, unless you specifically initialize them. In particular, all the values in arrayy will be "random" until you set them. In your first snippet, you set arrayy[inc], and then print it; this works as you expect. In your second snippet, you set arrayy[inc], and then print arrayy[inc + 1] (since you have already incremented inc at this point). But you haven't yet set arrayy[inc + 1] to anything, so the value printed is "random".

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490048

In the second one, you're setting a value to 0, then incrementing inc, so the value you print out is the one just after what you just set to 0. Since it hasn't been initialized (yet), it produces arbitrary ("random") values.

It also prints out the value one past the end of the array, giving undefined behavior when it does so.

Upvotes: 3

Related Questions