What is '\0' in C++? - c++

I'm trying to translate a huge project from C++ to Delphi and I'm finalizing the translation. One of the things I left is the '\0' monster.
if (*asmcmd=='\0' || *asmcmd==';')
where asmcmd is char*.
I know that \0 marks the end of array type in C++, but I need to know it as a byte. Is it 0?
In other words, would the code below be the equivalent of the C++ line?
if(asmcmd^=0) or (asmcmd^=';') then ...
where asmcmd is PAnsiChar.
You need not know Delphi to answer my question, but tell me \0 as byte. That would work also. :)

'\0' equals 0. It's a relic from C, which doesn't have any string type at all and uses char arrays instead. The null character is used to mark the end of a string; not a very wise decision in retrospect - most other string implementations use a dedicated counter variable somewhere, which makes finding the end of a string O(1) instead of C's O(n).
*asmcmd=='\0' is just a convoluted way of checking length(asmcmd) == 0 or asmcmd.is_empty() in a hypothetical language.

Strictly it is an escape sequence for the character with the octal value zero (which is of course also zero in any base).
Although you can use any number prefixed with zero to specify an octal character code (for example '\040' is a space character in ASCII encoding) you would seldom ever have cause to do so. '\0' is idiomatic for specifying a NUL character (because you cannot type such a character from the keyboard or display it in your editor).
You could equally specify '\x0', which is a NUL character expressed in hexadecimal.
The NUL character is used in C and C++ to terminate a string stored in a character array. This representation is used for literal string constants and by convention for strings that are manipulated by the<cstring>/<string.h>library. In C++ the std::string class can be used instead.
Note that in C++ a character constant such as '\0' or 'a' has type char. In C, for perhaps obscure reasons, it has type int.

That is the char for null or char value 0. It is used at the end of the string.

Related

Why doesn't strlen() count the byte of the terminating NUL-character, when the NUL-character is defined to be part of a string?

I know that strlen() does not count the NUL-terminating character with. I really know that this is a fact. Thus, this question is NOT about asking for why strlen() might "presumably" not return the right string length, which is already asked and answered alot well here on StackOverflow, f.e. in this thread, or this one.
So lets go ahead to my question:
In ISO/IEC 9899:1990 (E); 7.1.1., is stated:
A string is a contiguous sequence of characters terminated by and including the first null character.
What is the reason, why strlen() deviate from this formed standard, and does not "want" to accept a string with its NUL-terminating character?
Why?
Because you would expect this pseudocode's assertion to hold true:
str1 = "foo"
str2 = "bar"
str3 = concatenate(str1, str2)
Assert strlen(str1) + strlen(s2) == strlen(str3)
If terminating '\0' was counted by strlen, above assertion would not hold, which would be much more of overall headache, than what the current C string behavior is. More importantly, it would in my opinion be quite unintuitive and illogical.
Taking your doubt as a reasonable point we can state that: The C-string consists of two parts:
the string's useful content ("the text");
the null terminating character;
The null terminating character is purely a technical measure for determination of the end of the string by the C-originated library functions. Still, if one types a declaration:
char * str = "some string";
they logically would rather expect its length to be 11 which is as many as they can see in this statement. Hence the strlen() value yields only the length of the part 1. of the string.
Not really an answer to your question, but consider this example:
char string[] = "string";
printf("sizeof: %zu\n", sizeof(string));
printf("strlen: %zu\n", strlen(string));
This prints
sizeof: 7
strlen: 6
So sizeof counts the \0, but strlen doesn't.
Questions like this, that ask why a certain age-old decision was made one way and not another way, are hard to answer. I can say that it's perfectly obvious to me, anyway, that strlen should count just the real, "interesting" characters that are in the string, and ignore the \0 at the end that merely terminates it. I'm used to accounting for the \0 separately. I imagine it would have been considerably more of a nuisance overall if strlen had been defined the other way. But I can't prove this with convincing arguments, and I've been using strlen with its current definition for so long that I'm probably hopelessly biased; I might be saying "it's perfectly obvious to me that..." even if strlen's definition were quite wrong.
There is a difference between the physical, stored representation of a C style string and the logical representation of a C style string.
The physical representation, how the string is actually stored in memory or other media includes the null character. The null character is included when discussing the physical representation because it take up an additional piece of storage. In order to be a C style string the null character must be stored.
However the logical representation of a string does not include the null character. The logical representation of a string includes only the text characters that the programmer is wanting to manipulate.
I suspect that the null character, a value of binary zero, was chosen because of the original ASCII character set defined a character value of zero as the NULL character. Part of the lower values among the various teletype control codes, it seems to be the least likely ASCII character that may appear in text. See ASCII Character Codes.
Another nice quality of using a binary zero as the string terminator is that is the value that represents logical false so iterating over a string is often a matter of incrementing an array index or incrementing a pointer while logical true since all characters other than the end of string indicator have a non-zero or logical true value.
Due to how close to the hardware that the C programming language is, the programmer needs to be concerned about both representations, the physical representation when allocating memory to store a string which includes the null character and the logical representation which is the string without the null character.
The various C style string manipulation functions in the Standard Library (strlen(), strcpy(), etc.) are all designed around the logical representation of a C style string. They perform their actions by using the null character as not being part of the text but rather as a special indicator character which indicates the end of the string. However as a part of their operations they need to be aware of the null character and its use as a special symbol. For instance when strcpy() or strcat() are used to copy strings, they must also copy the null character that indicates the end of the string even though it is not part of the actual text of the logical representation.
This choice allows text strings to be stored as arrays of characters, as befits the hardware orientation and efficiency characteristics of C. There is no need to create an additional built in type for text strings and it fits well with the lean character of the C programming language.
C++ is able to provide the std::string because of being object oriented and having the additional facilities of the language that allows for objects to be created and managed. The C programming language, due to its simple syntax and lack of object oriented facilities does not have this convenience.
The problem with this approach is that the programmer needs to be aware of both the physical representation and the logical representation of text strings and be able to accommodate the needs of both when writing programs.

C++: What if theres a null character before any other character in an array?

If we're outputting said array and the first character is \0, is it just ignored and the next character that isn't null treated as the first character?
Depends on the 'outputting' function...if it knows the length of the array, it could output every element regardless of value. Most functions working with 'C strings' will stop at the first \0.
C-styled strings are by default, sentinel character arrays meaning they terminated at the first appearance of \0 (or some form of null), so it shouldn't be ignored. It should terminate the string, treating it as an empty string.
By convention, if the "C string" (read char array) uses "string-ish" methods to do something with the string, it will stop at the first ASCII-zero (length parameters are regarded as "up-to" lengths). If it uses "array-ish" methods, it will regard a length parameter as a "precisely" length and iterate a for loop from zero to that size. The latter can often be found in binary handling, while the former is convention for string treatment of char arrays.
Examples in C standard headers are memxyz functions for binary array as opposed to strnxyz functions for strings.

Null-terminate string: Use '\0' or just 0?

If I need to null-terminate a String, should I rather use \0 or is a simple 0 also enough?
Is there any difference between using
char a[5];
a[0] = 0;
and
char a[5];
a[0] = '\0';
Or is \0 just preferred to make it clear that I'm null-terminating here, but for the compiler it is the same?
'\0' is an escape sequence for an octal literal with the value of 0. So there is no difference between them
Side note: if you are dealing with strings than you should use a std::string.
Use '\0' or just 0?
There is no difference in value.
In C, there is no difference in type: both are int.
In C++ they have different types: char and int. So the edge goes to '\0' as there is no type conversion involved.
Different style guides promote one over the other. '\0' for clarity. 0 for lack of clutter.
Right answer: Use the style based on your group's coding standards/guidelines. If you group does not have such guideline, make one. Better to use one than have divergent styles.
'\0' is exactly the same as 0 despite of the type. '\0' is just a representation as a char literal. The type char can be initialized from plain int literals though.
So it's actually impossible to tell what's better, just keep in mind to use it consistently in your code.
Both will generate the same machine code, as 0 will be converted to the character value 0, and '\0' is just another way of writing the character value 0. The latter is clearly a character, so it will show that you didn't accidentally mean to write '0' instead, but other than that, it's exactly the same thing in the end.
It's the same thing. Look at the ascii table.
It's better from my point of view to use '\0' because you explicity say that the end of string.
That help when you read your code (like using NULL for pointer instead of 0).

Why are strings in C++ usually terminated with '\0'?

In many code samples, people usually use '\0' after creating a new char array like this:
string s = "JustAString";
char* array = new char[s.size() + 1];
strncpy(array, s.c_str(), s.size());
array[s.size()] = '\0';
Why should we use '\0' here?
The title of your question references C strings. C++ std::string objects are handled differently than standard C strings. \0 is important when using C strings, and when I use the term string in this answer, I'm referring to standard C strings.
\0 acts as a string terminator in C. It is known as the null character, or NUL, and standard C strings are null-terminated. This terminator signals code that processes strings - standard libraries but also your own code - where the end of a string is. A good example is strlen which returns the length of a string: strlen works using the assumption that it operates on strings that are terminated using \0.
When you declare a constant string with:
const char *str = "JustAString";
then the \0 is appended automatically for you. In other cases, where you'll be managing a non-constant string as with your array example, you'll sometimes need to deal with it yourself. The docs for strncpy, which is used in your example, are a good illustration: strncpy copies over the null terminator character except in the case where the specified length is reached before the entire string is copied. Hence you'll often see strncpy combined with the possibly redundant assignment of a null terminator. strlcpy and strcpy_s were designed to address the potential problems that arise from neglecting to handle this case.
In your particular example, array[s.size()] = '\0'; is one such redundancy: since array is of size s.size() + 1, and strncpy is copying s.size() characters, the function will append the \0.
The documentation for standard C string utilities will indicate when you'll need to be careful to include such a null terminator. But read the documentation carefully: as with strncpy the details are easily overlooked, leading to potential buffer overflows.
Why are strings in C++ usually terminated with '\0'?
Note that C++ Strings and C strings are not the same.
In C++ string refers to std::string which is a template class and provides a lot of intuitive functions to handle the string.
Note that C++ std::string are not \0 terminated, but the class provides functions to fetch the underlying string data as \0 terminated c-style string.
In C a string is collection of characters. This collection usually ends with a \0.
Unless a special character like \0 is used there would be no way of knowing when a string ends.
It is also aptly known as the string null terminator.
Ofcourse, there could be other ways of bookkeeping to track the length of the string, but using a special character has two straight advantages:
It is more intuitive and
There are no additional overheads
Note that \0 is needed because most of Standard C library functions operate on strings assuming they are \0 terminated.
For example:
While using printf() if you have an string which is not \0terminated then printf() keeps writing characters to stdout until a \0 is encountered, in short it might even print garbage.
Why should we use '\0' here?
There are two scenarios when you do not need to \0 terminate a string:
In any usage if you are explicitly bookkeeping length of the string and
If you are using some standard library api will implicitly add a \0 to strings.
In your case you already have the second scenario working for you.
array[s.size()] = '\0';
The above code statement is redundant in your example.
For your example using strncpy() makes it useless. strncpy() copies s.size() characters to your array, Note that it appends a null termination if there is any space left after copying the strings. Since arrayis of size s.size() + 1 a \0 is automagically added.
'\0' is the null termination character. If your character array didn't have it and you tried to do a strcpy you would have a buffer overflow. Many functions rely on it to know when they need to stop reading or writing memory.
strncpy(array, s.c_str(), s.size());
array[s.size()] = '\0';
Why should we use '\0' here?
You shouldn't, that second line is waste of space. strncpy already adds a null termination if you know how to use it. The code can be rewritten as:
strncpy(array, s.c_str(), s.size()+1);
strncpy is sort of a weird function, it assumes that the first parameter is an array of the size of the third parameter. So it only copies null termination if there is any space left after copying the strings.
You could also have used memcpy() in this case, it will be slightly more efficient, though perhaps makes the code less intuitive to read.
In C, we represent string with an array of char (or w_char), and use special character to signal the end of the string. As opposed to Pascal, which stores the length of the string in the index 0 of the array (thus the string has a hard limit on the number of characters), there is theoretically no limit on the number of characters that a string (represented as array of characters) can have in C.
The special character is expected to be NUL in all the functions from the default library in C, and also other libraries. If you want to use the library functions that relies on the exact length of the string, you must terminate the string with NUL. You can totally define your own terminating character, but you must understand that library functions involving string (as array of characters) may not work as you expect and it will cause all sorts of errors.
In the snippet of code given, there is a need to explicitly set the terminating character to NUL, since you don't know if there are trash data in the array allocated. It is also a good practice, since in large code, you may not see the initialization of the array of characters.

How to get a C-string out of a string that contains \0 without losing the \0

I currently have a pretty huge string. I NEED to convert it into a C-string (char*), because the function I want to use only take C-string in parameter.
My problem here is that any thing I tried made the final C-string wayyy smaller then the original string, because my string contains many \0. Those \0 are essential, so I can't simply remove them :(...
I tried various way to do so, but the most common were :
myString.c_str();
myString.data();
Unfortunately the C-string was always only the content of the original string that was before the first \0.
Any help will be greatly appreciated!
You cannot create a C-string which contains '\0' characters, because a C-string is, by definition, a sequence of characters terminated by '\0' (also called a "zero-terminated string"), so the first '\0' in the sequence ends the string.
However, there are interfaces that take a a pointer to the first character and the length of the character sequence. These might be able to deal with character sequences including '\0'.
Watch out for myString.data(), because this returns a pointer to a character sequence that might not be zero-terminated, while mystring.c_str() always returns a zero-terminated C-string.
This is not possible. The null is the end of a null terminated string. If you take a look at your character buffer (use &myString[0]), you'll see that the NULLs are still there. However, no C functions are going to interpret those NULLs correctly because NULL is not a valid value in the middle of a string in C.
Well, myString has probably been truncated at construction/assignment time. You can try std::basic_string::assign which takes two iterators as arguments or simply use std::vector <char>, the latter being more usual in your use case.
And your API taking that C string must actually support taking a char pointer together with a length.
I'm a bit confused, but:
string x("abc");
if (x.c_str()[3] == '\0')
{ cout << "there it is" << endl; }
This may not meet your needs, you did say 'Those \0 are essential', but how about escaping or replacing the '\0' chars?
Would one of these ideas work?
replace the '\0' chars with a '\t' (tab char, decimal 9).
replace the '\0' with some rarely used char value like decimal 1, or decimal 255.
Create an escape code, say by replacing each '\0' char with a coded substring, (like octal as in "\000"). (Be sure to replace any original '\' with a coded value as well (like "\134")).