Ioannis said:
char *s="whatever"; is not an error and i don't think any copiler exists
that ould give a warning about this. If it did, we would get thousands of
warnings in cases like this:
It's not (strictly speaking) an error, but it does use a deprecated and
unsafe conversion. My compiler warns about it, because I ask it to.
void whatever(char *);
/// ...
// We would get a warning
whatever("something")'
A warning here is completely appropriate, in my opinion. You would
expect a diagnostic if you did this, wouldn't you?
const char example[] = "something";
whatever(example);
The key point here is that both calls, your example and mine, pass an
object of exactly the same type. Your example may or may not give a
warning, but in my opinion it's best if it does. My example requires a
diagnostic. Both (if allowed) are unsafe in exactly the same way. That
being that whatever() may do something like this:
void whatever(char *p)
{
*p = '\0';
}
If, on the other hand, whatever() is not intended to modify the thing
its parameter points to, it should be declared like this:
void whatever(const char *p);
Now both examples are safe and silent.
whatever( something_else() );
Even strcpy() family for example would give warnings in the case:
strcpy(destination, "something");
No, because the second parameter has type const char *.
If you want to check the standard you can find this in D.4
[depr.string]. There's also information in 4.2/2 [conv.array]. Finally,
2.13.4 explicitly states that string literals consist of const
characters, and I know it's stated somewhere that modifying const
objects gives undefined behavior, but I'm not sure where to look.
Yes noone suggested modify string literals.
But making use of the deprecated conversion from a string literal to a
(non-const) char* allows code that does exactly that, without the
compiler being able to catch and diagnose it. This (and future
compatibility) is why you should not use this conversion.
My point is that using an object by mistake in a way not intended to will
invoke undefined behaviour anyway. Premature initialisation does not protect
us from any of our mistakes. E.g.
I wasn't advocating an "always initialize, even if the value is not
meaningful" policy, just stating the facts as giving by the language
definition.
My personal preference is to always initialize, but do so at the point
the object is needed, not before. In other words, don't create an object
(initialized or otherwise) until you need it, then create and initialize
at the same time.
-Kevin