简体   繁体   中英

Why does gcc compiler behave differently in these two cases?

I have two similar while loops and am curious why C compiler behaves differently in each case.

Details: Compiler: x86-64 gcc 8.2

Options: -O3

void use() 
{ 
    int* ptr;
    while (*ptr == 6);
}

Assembly:

use:
        cmp     DWORD PTR ds:0, 6
        jne     .L1
.L3:
        jmp     .L3
.L1:
        ret

As we see, the compiler still generates an infinite loop. However, if I use this:

void use() 
{ 
    int p;
    while (p == 6);
} 

Assembly:

use:
        ret

I expected both of them to generate no while loop. My guess is that, for 1st version, since we cannot possibly know what ptr points to, we cannot assume anything about *ptr. But could we make a similar argument for the 2nd version, where p is just a local variable, ie p could contain anything?

Both versions have Undefined Behavior because you access and read uninitialized variables. As such the compiler can generate any code.

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