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++.
 
Back
Top