gpt4 book ai didi

c - C中的const限定符深入剖析

转载 作者:太空狗 更新时间:2023-10-29 16:58:14 24 4
gpt4 key购买 nike

const 变量究竟存储在哪里?它的行为如何改变?比如说:

const int i=10; // stores where ?  
main()
{
const int j=20; //stores where?
return 0;
}

如果答案是代码段那么下面的代码是如何工作的??

main()  
{
const int j=20;
int *p;
p=&j;
(*p)++;
return 0 ;
}

此代码工作正常...如何更改只读内存?它是如何真正存储的?请详细解释一下。

最佳答案

关键字 const 表示一个只读变量(即不能在运行时更改)。它不表示编译时常量。因此,变量的所有常用属性都适用;具体来说,就是分配了可寻址的存储空间。

#define 不同,您的常量不一定由编译器内联。相反,编译器将创建一个与目标文件中的 const 声明相对应的符号,以便可以从其他代码文件访问它——请记住 const 对象具有外部链接C 中的默认值(尽管某些编译器仍会在定义它的文件中内联常量值)。

您发布的代码片段“有效”的原因是因为一元运算符 & 可以应用于任何左值,其中包括 const 对象。虽然此处的行为未定义,但我怀疑您的编译器正在检测此用法并确保为您的 const 声明提供地址空间,因此即使在声明的文件中也不会内联它。

编辑:另见:http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html

Let's look at what is meant when const is used. It's really quite simple: const means that something is not modifiable, so a data object that is declared with const as a part of its type specification must not be assigned to in any way during the run of a program. It is very likely that the definition of the object will contain an initializer (otherwise, since you can't assign to it, how would it ever get a value?), but this is not always the case. For example, if you were accessing a hardware port at a fixed memory address and promised only to read from it, then it would be declared to be const but not initialized.

Taking the address of a data object of a type which isn't const and putting it into a pointer to the const-qualified version of the same type is both safe and explicitly permitted; you will be able to use the pointer to inspect the object, but not modify it. Putting the address of a const type into a pointer to the unqualified type is much more dangerous and consequently prohibited (although you can get around this by using a cast). For example...

关于c - C中的const限定符深入剖析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4275504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com