问题描述
以下code显示使用具有gcc和g ++不同的输出常量
变量 I
。
的地址 I
和值 PTR
是一样的,但对印刷<$ C $价值访问该地址C> I 和derefrencing PTR
我我为 5
与G ++和 10
与海湾合作委员会。
如何G ++在内存中保存const的变量?
的#include&LT;&stdio.h中GT;
诠释的main()
{
const int的I = 5;
为int * PTR =(INT *)及我;
* PTR = 10;
的printf(\\ n%u和%u和%D和%d个\\ n,&安培;我,PTR,我,* PTR); 返回0;
}
您正在修改常量
限定的对象。这是不是在C允许的(未定义的行为)。任何事情都有可能发生。
例如:
- 编译器可以把
I
成只读存储器。写* PTR
将你的程序崩溃。 - 这可以把它变成可写内存,你会只看到10。
- 这可以把它变成可写内存,但更换所有的读访问
I
按数字5(你答应这是常量
,不是吗?)。
我猜的C编译器选择2,而C ++编译器去3。
The following code shows different output with gcc and g++ on using const
variable i
.The addresses of i
and value of ptr
is same, but on accessing that address by printing value of i
and derefrencing value of ptr
I got value of i
as 5
with g++ and 10
with gcc.
How g++ holds const variable in memory?
#include <stdio.h>
int main()
{
const int i =5;
int *ptr =(int*)&i;
*ptr = 10;
printf("\n %u and %u and %d and %d \n",&i,ptr,i,*ptr);
return 0;
}
You are modifying a const
qualified object. This is not allowed in C ("undefined behavior"). Anything can happen.
Examples:
- The compiler could put
i
into read-only memory. Writing to*ptr
would crash your program. - It could put it into writable memory and you would just see the 10.
- It could put it into writable memory but replace all read accesses to
i
by the number 5 (You promised it isconst
, didn't you?).
I guess the C compiler chose 2 while the C++ compiler went for 3.
这篇关于相同的地址显示了常量与变量G ++编译器不同的价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!