简体   繁体   中英

Can someone explain to me why this code doesn't output anything

I've already broken my head over what's wrong here. In the output I literally get nothing. It is very strange that nothing is output through a normal cout .

Help me please. Thank you.

int main() {
    int x = 111111;
    array<int, 10> numbers;
    numbers.fill(8);
    const auto numbers_copy = numbers;
    int y = 222222;
    
    for (int* i = &y; i <= &x; i++) {
        cout << *i << ' ';
    }
    cout << endl;
}

This loop:

for (int* i = &y; i <= &x; i++) {

has undefined behavior (UB) .

Comparing pointers to unrelated objects has unspecified results. In this case i is pointing to 2 different int objects, x and y , so the first comparison may or may not be true, because there is no guarantee that 2 objects on the stack will be placed one after the other contiguously in memory, or in any particular order.

The same applies to the second iteration of the loop. In the second iteration, when you do i++ for the second time, this is undefined behavior, since you can't increment i that far when it points to an int .

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