su**************@yahoo.com, India wrote:
Suppose we have
char *a = "test message" ;
Consider the comparison
if (a == "string")
.....
Here "string" is an array of characters. So shouldn't the compiler
generate an error/warning for this comparison ?
It's not required to generate a disgnostic. A good warning
for this wouldn't look like the one you're thinking of.
In the expression `a == "string"`, the literal is evaulated
in what I shall call "value" context, as opposed to "target of
assignment" context [1] or "operand of sizeof" context.
Remember that a string literal denotes an array, and that an
array in value context decays into a pointer to its first
element.
So we're comparing `a`, which is a pointer-to-char, to the
address of the `s` in `"string"`, which is pointer-to-char.
No problem, no diagnostic. Happy times!
But [2] ... this is a pretty useless comparision, and not just
because we know that `a` points to a different string; it's
worse than that, Jim.
The only way for the comparision to be true is if `a` points
to that very same `s`. Can it? At first glance no, because
there's no other variable referring to that `s`, and no
other path to get to that literal. So perhaps the compiler
should warn "comparision can never succeed"? Again no: suppose
we had
char *a = strchr( "long string", 's' );
so that it points to the `s` in "long string". The compiler
is /permitted/ to have the literal "string" share store with
the tail of "long string".
So the warning might be something like
"that comparision doesn't have a stable result, because
it depends whether whatever `a` points to is part of
some string literal somewhere in this program that ends
with `string`. I suggest you don't do that. Maybe you
should be using `strcmp`?"
And you have to rush out and buy a bigger monitor.
[1] Which I'd call "lvalue" context except I'd risk confusion
and a flame war.
[2] You knew I was going to say that.
--
Chris "electric hedgehog" Dollin
The shortcuts are all full of people using them.