相关疑难解决方法(0)

"static const"vs"#define"vs"enum"

在C中的以下陈述中哪一个更好用?

static const int var = 5;
Run Code Online (Sandbox Code Playgroud)

要么

#define var 5
Run Code Online (Sandbox Code Playgroud)

要么

enum { var = 5 };
Run Code Online (Sandbox Code Playgroud)

c constants

550
推荐指数
12
解决办法
33万
查看次数

static const vs #define

使用static constvars比#define预处理器更好吗?或者也许取决于背景?

每种方法的优点/缺点是什么?

c c++ const

200
推荐指数
6
解决办法
14万
查看次数

字符串文字的C优化

刚刚在gdb中检查以下内容:

char *a[] = {"one","two","three","four"};
char *b[] = {"one","two","three","four"};
char *c[] = {"two","three","four","five"};
char *d[] = {"one","three","four","six"};
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

(gdb) p a
$17 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p b
$18 = {0x80961a4 "one", 0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four"}
(gdb) p c
$19 = {0x80961a8 "two", 0x80961ac "three", 0x80961b2 "four", 0x80961b7 "five"}
(gdb) p d
$20 = {0x80961a4 "one", 0x80961ac "three", 0x80961b2 "four", 0x80961bc "six"}
Run Code Online (Sandbox Code Playgroud)

我真的很惊讶字符串指针对于相同的单词是相同的.我原以为每个字符串都会在堆栈上分配自己的内存,无论它是否与另一个数组中的字符串相同.

这是某种编译器优化的示例,还是这种字符串声明的标准行为?

c string gcc compiler-optimization string-pool

22
推荐指数
2
解决办法
3746
查看次数

标签 统计

c ×3

c++ ×1

compiler-optimization ×1

const ×1

constants ×1

gcc ×1

string ×1

string-pool ×1