Infinity_hunter
Infinity_hunter

Reputation: 157

Initializing the string in C; Is the following useful?

I know how to initialize strings in C in two different ways.

char str[] = "abcd";

char str[] = {'a','b','c','d','\0' };

Clearly writing "abcd" instead of {'a','b','c','d','\0' } is time saving and comfortable.

Are there any particular reason that we can initialize the string like in the last line? Is it useful in some context or is it superfluous?

Upvotes: 3

Views: 684

Answers (2)

Steve Summit
Steve Summit

Reputation: 48026

The char str[] = {'a','b','c','d','\0' } form is rarely useful for initializing real strings, it's true.

I once wrote some code to filter out accidentally obscene words from generated text, and in a fit of self-censorship, I initialized the array of words to look for in a way that wouldn't offend the eyes of any future maintenance programmer:

char badwords[][5] = {
    { 's', 0x68, 105, 0164, '\0' },
    { 'p', 0151, 0x73, 115, '\0' },
    { 'c', 117, 0156, 0x74, '\0' },
    { 'f', 0x75, 0143, 107, '\0' },
    /* ... */
};

Upvotes: 3

Lundin
Lundin

Reputation: 214730

In general terms, no there isn't a difference. With some advanced exceptions, as follows...

  • In some cases you want a character array which is not a valid C string - that is, not null terminated. Then the latter form must be used. There's only some very special cases where such strings are needed though: very ancient Unix code and certain embedded systems implementations.

  • Another advantage of the latter form is better escape sequences. Escape sequences for string literals is a bit broken. Suppose I wish to print an extended symbol with code 0xAA and then the string "ABBA". puts("\xAAABBA"); won't compile since it takes everything behind the \x as hex. char str[] = {'\xAA','A','B','B','A','\0'}; puts(str); works fine though. (You can however split the string literal in several too, to achieve the same: "\xAA" "ABBA".)

  • Initialization with string literals also has the subtle but severe C language flaw discussed here:
    Inconsistent gcc diagnostic for string initialization

Upvotes: 5

Related Questions