在C语言中,如何指定变量为常量?

6

我知道可以使用#define宏来声明常量。通过这种方式,定义整数、浮点数或字符字面值为常量将变得简单。

但是,对于更复杂的数据结构,如数组或结构体,例如:

typedef struct {
    int name;
    char* phone_number;
} person;

我希望能够初始化一次,然后使其成为一个不可编辑的结构体。
在面向对象的语言中,存在“final”关键字可以轻松实现此功能,但是在C语言中没有这样的东西。我想到的一个解决方法是使用“setjmp”和“longjmp”来模拟try-catch括号并在检测更改时进行回滚。您需要将备份存储在文件/内存对象中,如果您要保护许多此类对象免受意外更改的影响,则可能会有点混乱。
问:是否可以在C语言中有效地表示这种模式?如果是,如何实现?

请删除c99标签,因为在C编程的开始时就可以声明变量为常量。 - Badda
当然,已经移除了那个标签。 - cs95
“_final是一个常见的关键字,指定声明为final的引用在初始化后不能被修改。_” 标签描述中所述。 - cs95
在面向对象的编程语言中,存在着 final 关键字可以轻松实现这一点。但是在 C++、C# 和 Python 中并没有 final 关键字。 - phuclv
3个回答

14

使用 const 作为变量关键字。这是一种防止值在后期被修改的方法。

const int a = 5;
a = 7; //Error, you cannot modify it!
例如在嵌入式系统中,如果可用的话,链接器可能会将这个变量存储到flash中。但并非必然如此。

1

const 是正确的选择。 const 是一个关键字,可能会告诉编译器两件事情:

  1. Enforce the constantness of an object.

    const YourType t;
    

    Declares a non-modifiable object. The compiler will force the const-correctness. It is important to note that the const-correctness is enforced conceptually by the compiler and there are ways to elude those rules.

  2. constantness of pointer (or to an access to an object)

    const int* pointer
    

    Declares a const pointer to an int (which is not const). It means that if there is a non-const pointer to that int then it can be modified.

更多信息请参见这个很棒的答案

1
在C语言中,相应的关键字是const

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接