Null-Terminated Strings
Null-Terminated Strings
Posted Nov 18, 2010 15:38 UTC (Thu) by etienne (guest, #25256)In reply to: Null-Terminated Strings by neilbrown
Parent article: Ghosts of Unix past, part 3: Unfixable designs
And you can also combine them to do things like:
enum {lang_english, lang_french, lang_german} current_language = lang_french;
const char mltstr_language[] = "english\0francais\0deutch\0"
const char *curlang(const char *mltstr)
{
/* select the right sub-string depending on current_language */
}
void fct(void)
{
printf ("LANG=%s", curlang(mltstr_language))
}
It saves *a lot of space* ; having strings, (aligned) pointers arrays everywhere, and worse having (aligned) size for pascal strings takes easily more memory than the program code and data altogether.
Posted Nov 18, 2010 17:24 UTC (Thu)
by pr1268 (guest, #24648)
[Link] (2 responses)
I like your code example, but it might only work in C (not C++). Two cases in point: 1 Stroustrup, B. The C++ Programming Language, Special Edition, p. 77
Posted Nov 19, 2010 10:58 UTC (Fri)
by etienne (guest, #25256)
[Link]
const char *curlang(const char *mltstr)
Oviously none of the substrings can have embedded zero char.
A C++ line of code like:
Posted Nov 20, 2010 1:03 UTC (Sat)
by cmccabe (guest, #60281)
[Link]
Sorry, you are confused. It works in both C++ and C.
> Using the enum value as an array index might give unpredictable results
Nope.
Here the enum is promoted to an integer. C++, like C, promotes a lot of types to integers under the right situations.
> The C++ standard library string can have '\0' characters anywhere inside
There is no std::string in this example. You are confused.
Null-Terminated Strings
2 Ibid, p. 583Null-Terminated Strings
{
const char *ptr = mltstr;
for (unsigned cptlang = 0; cptlang < current_language; cptlang++)
while (*ptr++) {}
return (*ptr)? ptr : mltstr;
}
cout << "The " << big? "big " : "small " << "dog is " << age << " year old.";
needs an efficient storage for small strings, even more when doing a multi language software.
Null-Terminated Strings
> since C++ treats enumerations as a distinct type (instead of int as in C)1
> the string (which may also lead to unpredictable behavior at runtime)2. Of
> course, you're referring to a C-style string, so this may be a moot point.
