如何在 C 语言中声明字符串常量?

我知道在 C 语言中声明数值常量为 enum而不是 #defineing 它们是很习惯的,或者至少是很好的风格。

/* bad style */
#define MAXLINE 1024


/* good/better style */
enum {
MAX_LINE = 1024
};

字符串常量的定义是否有等效的规则?

/* is this good style? */
#define HELLO "Hello World"


/* or is this better? */
const char *HELLO2 = "Howdy";

你更喜欢哪种方法? 如果可能的话,展示这两种方法的一些缺点。

236349 次浏览

One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:

#define HELLO "hello"
#define WORLD "world"


puts( HELLO WORLD );

Not sure that's really an advantage, but it is a technique that cannot be used with const char *'s.

The main disadvantage of the #define method is that the string is duplicated each time it is used, so you can end up with lots of copies of it in the executable, making it bigger.

There's one more (at least) road to Rome:

static const char HELLO3[] = "Howdy";

(static — optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*, because then you'll be able to use sizeof(HELLO3) and therefore you don't have to postpone till runtime what you can do at compile time.

The define has an advantage of compile-time concatenation, though (think HELLO ", World!") and you can sizeof(HELLO) as well.

But then you can also prefer const char* and use it across multiple files, which would save you a morsel of memory.

In short — it depends.

If you want a "const string" like your question says, I would really go for the version you stated in your question:

/* first version */
const char *HELLO2 = "Howdy";

Particularly, I would avoid:

/* second version */
const char HELLO2[] = "Howdy";

Reason: The problem with second version is that compiler will make a copy of the entire string "Howdy", PLUS that string is modifiable (so not really const).

On the other hand, first version is a const string accessible by pointer HELLO2, and it can not be modified.

Their are a few differences.

#define HELLO "Hello World"

The statement above can be used with preprocessor and can only be change in the preprocessor.

const char *HELLO2 = "Howdy";

The statement above can be changed with c code. Now you can't change the each individual character around like the statement below because its constant.

HELLO2[0] = 'a'

But you what you can do is have it point to a different string like the statement below

HELLO2 = "HELLO WOLRD"

It really depends on how you want to be able to change the variable around. With the preprocessor or c code.