As we all know, strings in C are null-terminated. Does that mean that according to the standard it is legal to use the NULL constant as the terminator? Or is the similarity of the name of NULL pointer and null-terminator for a string only a happy coincidence?
Consider the code:
char str1[] = "abc";
char str2[] = "abc";
str1[3] = NULL;
str2[3] = '\0';
Here, we change the terminator of str1
to NULL. Is this legal and well-formed C code and str1
adheres to C's definition of null-terminated string? Will it be the same in case of C++?
In practice, I have always used NULL instead of '\0' in my code for strings and everything worked - but is such practice 100% legal?
EDIT: I understand that it's very bad style and refrain from endorsing it and now understand the difference between 0, NULL and '\0' (as in a duplicate What is the difference between NULL, '\0' and 0). I'm still quite curious as for the legality of this code - and voices here seem to be mixed - and the duplicate does not give an authoritative answer to that in my opinion.