常见应用场景
定义硬件寄存器地址
- const volatile uint32_t *const UART_STATUS_REG = (uint32_t*)0x4000;
- // 解释:
- // - 第一个const:寄存器值可能被硬件改变,但代码不能写
- // - volatile:防止编译器优化
- // - 第二个const:固定指向该地址
保护数组/字符串
- void process_data(const int arr[], int len) {
- // 函数内不能修改arr[]的内容
- }
- const char *error_msg = "Fatal Error";
- // error_msg[0] = 'f'; // 错误!字符串字面量本身不可修改
配合extern共享常量
- // file1.c
- extern const int GLOBAL_CONST; // 声明
- // file2.c
- const int GLOBAL_CONST = 100; // 定义
|