adnan_e
adnan_e

Reputation: 1799

Why do we put the null terminator in brace enclosed char array initialization

I noticed that in many books and online tutorials when C strings are initialized using brace enclosed lists, it is done like this:

char string[100] = {'t', 'e', 's', 't', '\0' };

Shouldn't all unspecified values automatically be set to 0 (aka '\0')?

I tested this on multiple versions of GCC and MSVC, all values are indeed set to zero, but I'm wondering if there's a specific reason for explicitly writing the null terminator when initializing.

Upvotes: 1

Views: 210

Answers (3)

The Vee
The Vee

Reputation: 11580

You're right (see "Initialization from brace-enclosed lists" here). But it's a good practice because this would also compile without complaints:

char string[4] = {'t', 'e', 's', 't'};

but wouldn't null-terminate anything, which would lead to errors whenever you would use that as a string. If you say

char string[4] = {'t', 'e', 's', 't', '\0'};

the compiler will know it's an error because the '\0' won't fit.

Note that it's superior even to

char string[100] = "test";

for the same reason:

char string[4] = "test";

does the same as the first example, not the second!

Upvotes: 4

user743382
user743382

Reputation:

It's to prevent silly mistakes. The first null character is required if the characters are to be interpreted as a string.

char string[4] = {'t', 'e', 's', 't'};

will happily compile, but will not be null-terminated.

char string[4] = {'t', 'e', 's', 't', '\0'};

will fail to compile, which is the point.

By explicitly specifying the null character, the compiler will verify that the array is large enough for its intended purpose.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Adding null terminator is absolutely unnecessary when you specify the size of your character array explicitly, and allocate more chars than is needed for the payload portion of your string. In this situation the standard requires that the remaining chars be initialized with zeros.

The only time when it is necessary is when you want the size of a null-terminated array to be determined automatically by the compiler, i.e.

char string[] = {'t', 'e', 's', 't', '\0' };
//         ^^

Upvotes: 1

Related Questions