gpt4 book ai didi

c 语言 - 我可以使用 const uint32_t 而不是#define

转载 作者:行者123 更新时间:2023-11-30 21:00:49 27 4
gpt4 key购买 nike

在下面的代码中,我可以使用 const uint32_t PERIPH_BASE_ADDR = 0x40000000; 而不是使用 #define 吗?

#ifndef MEMORY_MAP_H_
#define MEMORY_MAP_H_

#include <stdint.h>

// Base address for devices on the STM32F10x
#define PERIPH_BASE_ADDR ((uint32_t)0x40000000) // Peripheral base address in the alias region

// Peripheral memory map
#define AHB1_BASE_ADDR ((uint32_t)(PERIPH_BASE_ADDR + 0x20000)) // Advanced High-performance Bus 1

#endif /* MEMORY_MAP_H_ */

最佳答案

当然可以。在头文件中,只需放入

static const uint32_t PERIPH_BASE_ADDR = (uint32_t) 0x40000000;
static const uint32_t AHB1_BASE_ADDR = (uint32_t) (PERIPH_BASE_ADDR + 0x20000);

#define 指令是一个预处理器指令;预处理器在编译器看到宏之前就用它们的宏体替换它们。将其视为源代码的自动搜索和替换。

const 变量声明在语言中声明了一个实际的变量,您可以使用它......就像一个真正的变量:获取它的地址,传递它,使用强制转换它,转换它,等等。

哦,性能:也许您认为避免声明变量可以节省时间和空间,但是对于任何合理的编译器优化级别,都不会有什么区别,因为常量值已经在编译时被替换和折叠。但是您获得了类型检查和让调试器知道您的代码的巨大优势,因此确实没有理由不使用 const 变量。

关于c 语言 - 我可以使用 const uint32_t 而不是#define,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38654597/

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