[c] How do you declare string constants in C?

I know it's quite idiomatic, or good style at least, in C to declare numeric constants as enums instead of #defineing them.

/* bad style */
#define MAXLINE 1024

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

Is there an equivalent rule for the definition of string constants?

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

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

What do you prefer? If possible show some drawbacks of either method.

This question is related to c string

The answer is


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.


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.


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.


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 const pointer HELLO2, and there is no way anybody can modify it.


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.