1

The code is:

#include<stdio.h>
int main()
{
    char *st1="hello";
    char *st2="hello";
    if(st1==st2)
        printf("equal %u  %u",st1,st2);
    else
        printf("unequal");
    return 0;
}

I am getting the output "equal 4206628 4206628".

Richa Tibrewal
  • 468
  • 7
  • 26
  • are the reported values actually 14206628 and 4206628, or is that extra 1 just a typo? – Steve Cox Mar 12 '15 at 15:11
  • 1
    `%u` expects and argument of type `unsigned int`. To print a pointer value, convert it to `void*` and use `%p`: `printf("equal %p %p\n", (void*)st1, (void*)st2);`. And you really want that newline at the end of your output. Incidentally, your program doesn't have a space in the output between the word "equal" and the value of st1. Please copy-and-paste both your actual code and your actual output; otherwise we can't guess which errors are in your code and which you introduced re-typing it. – Keith Thompson Mar 12 '15 at 15:18
  • @KeithThompson I marked it as the wrong duplicate, because I didn't see that it said **"equal"** now I can't fix it. Could you please? – Iharob Al Asimi Mar 12 '15 at 15:20
  • @iharob: Apparently I can't. I re-opened it, but when I tried to vote to close it again (as a duplicate of http://stackoverflow.com/q/11399682/827263) it told me I had already voted to close it. I'll flag it for moderator attention. – Keith Thompson Mar 12 '15 at 15:27

1 Answers1

6

st1 and st2 are pointers to read-only string literals. (Really you should use const char* as the type but compilers are relaxed about this.)

On this particular occasion, the compiler has optimised the code so only one string literal is stored. This optimisation is permitted since the C standard states that any attempt to modify a read-only string is undefined behaviour. So the pointers have the same address. Hence st1 == st2 (which compares the pointer addresses not the contents) is true.

The C standard does not mandate this behaviour, so don't rely on it.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483