Re: string comparison
On 9 Aug 2005 03:38:58 -0700, junky_fellow@ya hoo.co.in wrote:
[color=blue]
>Consider the following piece of code:
>char *str = "Hello";
>if (str = "Hello")
> printf("\nstrin g matches\n");
>
>str is pointer to char and "Hello" is a string literal whose
>type is "array of char".
>
>How can we compare two different objects for equality ?
>Is some conversion is being done before that comparison ?
>If yes, which conversion rule from C standard is applied here ?[/color]
After fixing the = to == in the if, the answer to your question is you
don't know if they are different objects. The compiler is allowed to
reuse string literals. It is entirely possible that str points to the
same string that is used in the if. It is also possible that str
points to a different string, even though the two strings contain same
six characters.
Just for fun, you might try
if ("Hello" == "Hello") ...
The same implementation defined behavior allows the expression to
evaluate to 1 or 0 as a result of how the compiler implements
duplicate string literals.
<<Remove the del for email>>
On 9 Aug 2005 03:38:58 -0700, junky_fellow@ya hoo.co.in wrote:
[color=blue]
>Consider the following piece of code:
>char *str = "Hello";
>if (str = "Hello")
> printf("\nstrin g matches\n");
>
>str is pointer to char and "Hello" is a string literal whose
>type is "array of char".
>
>How can we compare two different objects for equality ?
>Is some conversion is being done before that comparison ?
>If yes, which conversion rule from C standard is applied here ?[/color]
After fixing the = to == in the if, the answer to your question is you
don't know if they are different objects. The compiler is allowed to
reuse string literals. It is entirely possible that str points to the
same string that is used in the if. It is also possible that str
points to a different string, even though the two strings contain same
six characters.
Just for fun, you might try
if ("Hello" == "Hello") ...
The same implementation defined behavior allows the expression to
evaluate to 1 or 0 as a result of how the compiler implements
duplicate string literals.
<<Remove the del for email>>
Comment