简体   繁体   English

奇怪的初始化优化

[英]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. UPDT好吧,我了解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? 但是如果我有2个彼此相邻放置的int var(请参见地址),为什么此代码不起作用?

p++;

The code has undefined behavior. 该代码具有未定义的行为。 Pointer is pointing to some garbage location. 指针指向某个垃圾位置。 Dereferencing it leads to unpredicted results. 取消引用它会导致意外结果。

What do you call corerct ? 你怎么称呼corerct It isn't guaranted, how variables will be stored, so ANY result is correct 它不保证如何存储变量,所以ANY结果都是正确的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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