Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing char arrays in a way similar to initializing string literals

Suppose I've following initialization of a char array:

char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'};

and I also have following initialization of a string literal:

char stringLiteral[]="hello world";

The only difference between contents of first array and second string is that second string's got a null character at its end.

When it's the matter of initializing a char array, is there a macro or something that allows us to put our initializing text between two double quotation marks but where the array doesn't get an extra null terminating character?

It just doesn't make sense to me that when a terminating null character is not needed, we should use syntax of first mentioned initialization and write two single quotation marks for each character in the initializer text, as well as virgule marks to separate characters.

I should add that when I want to have a char array, it should also be obvious that I don't want to use it with functions that rely on string literals along with the fact that none of features in which using string literals results, is into my consideration.

I'm thankful for your answers.

like image 426
Pooria Avatar asked Jul 09 '10 20:07

Pooria


1 Answers

It's allowed in C to declare the array as follows, which will initialize it without copying the terminating '\0'

char c[3] = "foo";

But it's illegal in C++. I'm not aware of a trick that would allow it for C++. The C++ Standard further says

Rationale: When these non-terminated arrays are manipulated by standard string routines, there is potential for major catastrophe.
Effect on original feature: Deletion of semantically well-defined feature.
Difficulty of converting: Semantic transformation. The arrays must be declared one element bigger to contain the string terminating ’\0’.
How widely used: Seldom. This style of array initialization is seen as poor coding style.

like image 95
Johannes Schaub - litb Avatar answered Oct 03 '22 23:10

Johannes Schaub - litb