Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identical string literals are considered equal? [duplicate]

Tags:

c

I have written the following program:

#include <stdio.h>

main()
{
    if("ddd" == "ddd")
        printf("equal");
    else
        printf("not equal");
}

The output is "equal", but according to me, the output should be "not equal" because the string literals are stored in the literal pool or some read only memory (I guess it depends on OS), so both strings should have two different addresses as they are stored at different addresses in memory.

Previously, I have done the same type of example (one year back), and that time the output was "not equal". Now, could anyone tell me, is this due to a change in the C standard, or am I missing something?

like image 790
debendra nath tiwary Avatar asked Feb 12 '26 19:02

debendra nath tiwary


2 Answers

It's unspecified for string literals with the same content to have the same address or not. So the output of your program could be equal or it could be not equal, your compiler happens to put them in the same place.

C11 6.4.5 String literals

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.

like image 147
Yu Hao Avatar answered Feb 15 '26 08:02

Yu Hao


Of course, what you do in that condition is a comparison between pointers (use strcmp to compare C strings).

So, I think it is a compiler translation/optimization that "maps" identical literals at the same location in the memory.

EDIT 1:

The following sample confirms what I wrote:

#include <stdio.h>

char* a = "ddd";
char* b = "ddd";
char* c = "ddd";

int main() {
    printf ("a => %p\nb => %p\nc => %p\n", a, b, c);
}

The previous program, compiled with gcc using -O0 and executed will print:

a => 0x40060c
b => 0x40060c
c => 0x40060c

I don't know how other compilers will treat the same situation.

like image 40
Filippo Lauria Avatar answered Feb 15 '26 08:02

Filippo Lauria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!