“ const”如何?实施? [英] How is "const" implemented?

查看:67
本文介绍了“ const”如何?实施?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C或C ++编译器(例如gcc)如何遵守 const 声明?

How does a compiler, C or C++, (for example, gcc) honors the const declaration?

例如,在以下代码中,编译器如何跟踪 :变量 ci const

For example, in the following code, how does the compiler keeps track that the variable ci is const and cannot be modified?

int
get_foo() {
    return 42;
}

void
test()
{
    int i = get_foo();
    i += 5;

    const int ci = get_foo();
    // ci += 7;  // compile error: assignment of read-only variable ?ci?
}


推荐答案

变量的符号信息(地址,类型等)。通常会有一个符号表,用于存储有关已声明的标识符的信息,每当遇到另一个对标识符的引用时都会进行查询。

Much like any other bit of symbol information for variables (address, type etc.). Usually there is a symbol table which stores information about declared identifiers, and this is consulted whenever it encounters another reference to the identifier.

(一个更有趣的问题是该知识是否仅在编译期间甚至运行时才存在。大多数语言在编译后都会丢弃符号表,因此即使标识符被声明为 const,您也可以操纵编译后的代码并强制使用新值。这需要复杂的运行时系统(和代码)签名)以防止这种情况。)

(A more interesting question is whether this knowledge is only present during compilation or even during runtime. Most languages discard the symbol table after compiling, so you can manipulate the compiled code and force a new value even if the identifier was declared 'const'. It takes a sophisticated runtime system (and code signing) to prevent that.)

这篇关于“ const”如何?实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆