问题
if(s.name=="kolkata")
{
printf("the details");
}
if(strcmp((s.name,"kolkata")==0)
{
printf("the details");
}
The first 'if' case has no syntax error still it doesn't work,while the second 'if' case does work very efficiently, why?
回答1:
It is not like the first case doesn't work at all, it just works in a way which is not intended.
As per the code,
if(s.name=="kolkata")
is an attempt to compare the pointers themselves. It does not compare the content of the memory location pointer by these pointers.
Coming to the point where you were expecting syntax errors, quoting C11
, chapter 6.5.9, the constraints of the Equality operator, (==
)
- both operands are pointers to qualified or unqualified versions of compatible types;
So,
if(s.name=="kolkata")
is a perfectly valid and legitimate C code, from syntactical point of view. Logically, when you're expecting to compare the contents of the memory area pointer by the pointers, this code is useless and makes no sense.
来源:https://stackoverflow.com/questions/36717188/the-if-case-in-this-code-doesnt-work-while-there-is-no-syntax-error