C中的const限定变量有哪些实际用途? [英] What are some practical uses for const-qualified variables in C?

查看:96
本文介绍了C中的const限定变量有哪些实际用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如最近几个问题所讨论的,在C中声明 const 限定的变量(而不是 const C ++中的变量,或C中指向 const 的指针)通常没有什么用。最重要的是,它们不能在常量表达式中使用。

As has been discussed in several recent questions, declaring const-qualified variables in C (as opposed to const variables in C++, or pointers to const in C) usually serves very little purpose. Most importantly, they cannot be used in constant expressions.

话虽如此, const的一些合法用法是什么 C中的限定变量?我可以想到最近在我使用过的代码中出现了一些问题,但是肯定会有其他问题。这是我的列表:

With that said, what are some legitimate uses of const qualified variables in C? I can think of a few which have come up recently in code I've worked with, but surely there must be others. Here's my list:


  • 将它们的地址用作指针的特殊标记值,以便永远不要与其他任何指针进行比较。例如: char * sentinel(void){static const char s;返还& s; } 或简单地 const char sentinel [1]; 因为我们只关心地址,所以实际上将对象写到该地址都没关系, const 的唯一好处是,编译器通常会将其存储在由 mmap 支持的只读内存中。可执行文件或零页的副本。

  • Using their addresses as special sentinel values for a pointer, so as never to compare equal to any other pointer. For example: char *sentinel(void) { static const char s; return &s; } or simply const char sentinel[1]; Since we only care about the address and it actually wouldn't matter if the object were written to, the only benefit of const is that compilers will generally store it in read-only memory that's backed by mmap of the executable file or a copy of the zero page.

使用 const 限定变量从a中导出值库(尤其是共享库)时,值可能会随库的新版本而更改。在这种情况下,仅在库的接口标头中使用 #define 并不是一种好方法,因为它将使应用程序依赖于特定版本的常量的值。

Using const qualified variables to export values from a library (especially shared libraries), when the values could change with new versions of the library. In such cases, simply using #define in the library's interface header would not be a good approach because it would make the application dependent on the values of the constants in the particular version of the library it was built with.

与以前的使用紧密相关,有时您希望将库中的预定义对象公开给应用程序(典型的例如,标准中的 stdin stdout stderr 图书馆)。使用该示例, extern FILE __stdin;由于大多数系统实现共享库的方式,#define stdin(& __ stdin)的实现将是非常糟糕的-通常它们需要整个对象(此处为 FILE )复制到链接应用程序时确定的地址,并引入对对象大小的依赖性(如果重建库并且对象大小改变,程序将中断)。使用 const 指针(而不是指向 const 的指针)可以解决所有问题: extern FILE * const stdin; ,其中 const 指针被初始化为指向预定义的对象(它本身很可能声明为 static )在库内部的某个位置。

Closely related to the previous use, sometimes you want to expose pre-defined objects from a library to the application (the quintessential examples being stdin, stdout, and stderr from the standard library). Using that example, extern FILE __stdin; #define stdin (&__stdin) would be a very bad implementation due to the way most systems implement shared libraries - usually they require the entire object (here, FILE) to be copied to an address determined when the application is linked, and introduce a dependency on the size of the object (the program will break if the library is rebuilt and the size of the object changes). Using a const pointer (not pointer-to-const) here fixes all the problems: extern FILE *const stdin;, where the const pointer is initialized to point to the pre-defined object (which itself is likely declared static) somewhere internal to the library.

查找表,用于查找数学函数,字符属性等。这是我最初忘记包括的一个显而易见的变量,可能是因为我在考虑算术/指针类型的各个 const 变量,因为这是问题主题首次出现的地方。感谢Aidan触发了我的记忆。

Lookup tables for mathematical functions, character properties, etc. This is the obvious one I originally forgot to include, probably because I was thinking of individual const variables of arithmetic/pointer type, as that's where the question topic first came up. Thanks to Aidan for triggering me to remember.

作为查找表的一种变体,状态机的实现。艾丹提供了一个详细的示例作为答案。我发现,如果您可以根据一些数字参数对每个状态的行为/转换进行编码,则没有任何函数指针,同样的概念通常也非常有用。

As a variant on lookup tables, implementation of state machines. Aidan provided a detailed example as an answer. I've found the same concept is also often very useful without any function pointers, if you can encode the behavior/transitions from each state in terms of a few numeric parameters.

其他人对于C中 const 限定的变量有一些聪明的实际用法吗?

Anyone else have some clever, practical uses for const-qualified variables in C?

推荐答案

const 经常在嵌入式编程中用于映射到微控制器的GPIO引脚。例如:

const is quite often used in embedded programming for mapping onto GPIO pins of a microcontroller. For example:


typedef unsigned char const volatile * const tInPort;
typedef unsigned char                * const tOutPort;

tInPort  my_input  = (tInPort)0x00FA;
tOutPort my_output = (tOutPort)0x00FC;

这两个都防止程序员意外更改指针本身,这在某些情况下可能是灾难性的。 tInPort 声明还阻止程序员更改输入值。

Both of these prevent the programmer from accidentally changing the pointer itself which could be disastrous in some cases. The tInPort declaration also prevents the programmer from changing the input value.

使用 volatile 防止编译器假定 my_input 的最新值将存在于缓存中。因此,从 my_input 进行的任何读取都会直接进入总线,因此总是从设备的IO引脚读取。

Using volatile prevents the compiler from assuming that the most recent value for my_input will exist in cache. So any read from my_input will go directly to the bus and hence always read from the IO pins of the device.

这篇关于C中的const限定变量有哪些实际用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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