1

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?

6
  • 1
    because strings are null-terminated? Commented 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. Commented Jan 25, 2014 at 13:26
  • That is life - bit boring Commented Jan 25, 2014 at 13:27
  • 1
    This 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. Commented Jan 25, 2014 at 13:29
  • Besides history, some functions (like strcmp) are more efficient not keeping track of the length of characters processed Commented Jan 25, 2014 at 13:43

3 Answers 3

5

Wikipedia:

"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'..."

Sign up to request clarification or add additional context in comments.

Comments

1

It is the best way to find end of the string from a chunk of memory! And the whole string library functions believe strings are null terminated ;)

Comments

0

Because C strings are null-terminated.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.