0

I was going through a site which had the following piece of code and the question following that was, what is the expected output?

#include<stdio.h>
main()
{
    char *foo = "Arista Netowrks";
    char *bar = "Arista Netowrks";
    printf("%d %d\n",foo,bar);
}

The answer given was Both the address would be same. As the strings are read only so they would behave as global constants in read only memory. I am adept in C but this totally took my off guard. I would be thoroughly obliged if someone could elaborate the answer mentioned above. I understand that the address will be printed and I understand that its read only memory. But how does it act as global constant if it was declared inside a function and how do both the variables point to it?

Source: GeeksforGeeks.org

Vinay Pai
  • 443
  • 1
  • 5
  • 13
  • 1
    Strictly speaking, this program causes undefined behaviour. Don't use `%d` to print pointers. – Carl Norum Oct 18 '13 at 05:03
  • 1
    This may answer your question: http://stackoverflow.com/questions/6281835/how-do-c-compilers-merge-identical-string-literals – Steve Oct 18 '13 at 05:06

0 Answers0