简体   繁体   中英

Strange optimization of initialization

I realize that my example not correct in general. But interesting to find out how it works.

/* C/C++ (gcc-4.3.4) */
#include <stdio.h>
int main() {

        /*volatile*/ int i = 5;
        int j = 500;

        int *p = &j;

        printf( "%d %x\n", *p, p );

        p++;

        printf( "%d %x\n", *p, p  ); // works correct with volatile (*p is 5)
        //printf( "%d %x\n", *p, &i  ); //  works correct without volatile

        return 0;
}

Is it some kind of optimization?

UPDT Ok i got about UB. I won't hope on another else.

BUT if i have 2 int vars which placed adjacent to each others (see addresses) why this code shouldn't works?

p++;

The code has undefined behavior. Pointer is pointing to some garbage location. Dereferencing it leads to unpredicted results.

What do you call corerct ? It isn't guaranted, how variables will be stored, so ANY result is correct

Both variables are not necessarly adjacent in memory. You could use an array to do this.

#define PRINT(p) (printf("%i %p\n", *(p), (void *)(p)))

int t[2];
int *a = &t[0];
int *b = &t[1];

*a = 5;
*b = 6;

int *p = a;
PRINT(p);

++p;
PRINT(p);

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