Trailing null?

  • Thread starter Thread starter Bob Altman
  • Start date Start date
B

Bob Altman

Hi all,

I inherited some unmanaged C++ code that is littered with statements like
this:

char x[] = "abc";

The author of the code expects these character arrays to be null terminated.
Is that how C++ treats thgese statements, or do I need to explicitly include
a trailing null in the character string?

TIA - Bob
 
Bob said:
Hi all,

I inherited some unmanaged C++ code that is littered with statements like
this:

char x[] = "abc";

The author of the code expects these character arrays to be null terminated.
Is that how C++ treats thgese statements, or do I need to explicitly include
a trailing null in the character string?

Bob:

The trailing null is appended.
 
Bob Altman said:
Hi all,

I inherited some unmanaged C++ code that is littered with statements like
this:

char x[] = "abc";

The author of the code expects these character arrays to be null
terminated. Is that how C++ treats thgese statements, or do I need to
explicitly include a trailing null in the character string?

The double quote syntax places a trailing NUL character automatically. It's
identical to:

char x[] = { 'a', 'b', 'c', 0 };
 
Hi all,

I inherited some unmanaged C++ code that is littered with statements like
this:

char x[] = "abc";

The author of the code expects these character arrays to be null terminated.
Is that how C++ treats thgese statements, or do I need to explicitly include
a trailing null in the character string?

String literals such as "abc" always have an implied nul terminator. For
the form of initialization above, the compiler sizes x per the size of the
literal, so x is char[4], and the compiler copies the nul along with the
rest of the data. So to answer your question, no, you don't need to do
anything.

In C, at least the 1989 version I know, it was possible to say:

char x[3] = "abc";

This would not copy the nul terminator, and x would be left unterminated.
This is disallowed in C++.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top