Monday, April 27, 2020

Digest for comp.lang.c++@googlegroups.com - 2 updates in 1 topic

Juha Nieminen <nospam@thanks.invalid>: Apr 27 12:06PM

> Another is that C++ string literals are const, so this:
> char *s = "hello";
> is invalid C++.
 
Wouldn't that be UB even in C?
 
(Ok, using a non-const pointer to point to a string literaly is not in
itsef UB, but if you ever try to modify it...)
 
I believe that most competent C programmers would never use non-const
char*'s to handle string literals (and most competent C compilers will
give a huge-ass warning about it).
James Kuyper <jameskuyper@alumni.caltech.edu>: Apr 27 10:11AM -0400

On 4/27/20 8:06 AM, Juha Nieminen wrote:
>> char *s = "hello";
>> is invalid C++.
 
> Wouldn't that be UB even in C?
 
No, it's code with perfect well-defined behavior. "hello" has the type
char[6], and in this context gets implicitly converted into a char*
pointing at the first element of that array. In C++, it has the type
const char[6], and gets implicitly converted to const char*. Assigning a
const char* value to a char* object would violate the rules of either
language, but it isn't a const char* in C.
 
> (Ok, using a non-const pointer to point to a string literaly is not in
> itsef UB, but if you ever try to modify it...)
 
Correct - any attempt to modify that string has undefined behavior. But
if no such attempt is made, the behavior is well-defined (though such
code is a potential trap for future maintainers of the code).
 
> I believe that most competent C programmers would never use non-const
> char*'s to handle string literals (and most competent C compilers will
> give a huge-ass warning about it).
 
A lot of people don't bother with that; they may not qualify as
"competent", but they're quite numerous, and a lot of them seem to be
currently earning money writing C code, so it is important to look out
for such problems.
You received this digest because you're subscribed to updates for this group. You can change your settings on the group membership page.
To unsubscribe from this group and stop receiving emails from it send an email to comp.lang.c+++unsubscribe@googlegroups.com.

No comments: