Tutorial :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.


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.


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

  #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.


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »