In C++ primer it is given that a null character is added at the end of every string literal. Why does a compiler do so?
- 1because strings are null-terminated?devnull– devnull2014-01-25 13:25:10 +00:00Commented Jan 25, 2014 at 13:25
- 1"Hello World" is defined to have that extra zero at the end - a c-language designer decided so.user2249683– user22496832014-01-25 13:26:55 +00:00Commented Jan 25, 2014 at 13:26
- That is life - bit boringEd Heal– Ed Heal2014-01-25 13:27:29 +00:00Commented Jan 25, 2014 at 13:27
- 1This question appears to be off-topic because it is about asking why are C-strings null-terminated. This is more appropriate for the language designers to answer.devnull– devnull2014-01-25 13:29:29 +00:00Commented Jan 25, 2014 at 13:29
- Besides history, some functions (like strcmp) are more efficient not keeping track of the length of characters processeduser2249683– user22496832014-01-25 13:43:59 +00:00Commented Jan 25, 2014 at 13:43
3 Answers
"At the time C (and the languages that it was derived from) was developed, memory was extremely limited, so using only one byte of overhead to store the length of a string was attractive. The only popular alternative at that time, usually called a "Pascal string" (though also used by early versions of BASIC), used a leading byte to store the length of the string. This allowed the string to contain NULL and made finding the length need only one memory access (O(1) (constant) time).
However, C designer Dennis Ritchie chose to follow the convention of NULL-termination, already established in BCPL 'to avoid the limitation on the length of a string caused by holding the count in an 8- or 9-bit slot, and partly because maintaining the count seemed, in our experience, less convenient than using a terminator'..."