Hardcoded Char Arrays

Hardcoded Char Arrays

Does your C++ compiler accept the following code?

 char s[3]="abc"; // illegal in C++, no place for ''

The standard requires that the size of a char array initialized with a literal string be sufficiently large to store a terminating null character. In other words, the declaration of s should be flagged as a compilation error because it contains only three positions instead of four. Unfortunately, the rules regarding static char arrays in C are less restrictive. Therefore, such a declaration is valid in C. Many C++ compilers still follows the old C rules and accept the declaration above when they shouldn’t. Using such an array is likely to cause undefined behavior because most functions that manipulate strings expect a null-terminated array.

See also  5 Benefits of Using Time Tracking Software

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist