简体   繁体   中英

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;
        
    }
}

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.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM