Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string literals are comparable with pointers? [duplicate]

If we say:

 char *p="name";

then how can we do

if(p=="name"){
 printf("able"};//this if condition is true but why?

as "name" here is a string literal and p is a pointer which holds the base address of the string then why the above statement works fine?

like image 888
OldSchool Avatar asked Mar 05 '14 13:03

OldSchool


2 Answers

It is unspecified behavior whether identical string literals can be considered the same and thus have the same address. So this is not portable behavior. From the draft C99 standard section 6.4.5 String literals:

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

If you want to compare two string you should use strcmp.

like image 160
Shafik Yaghmour Avatar answered Nov 10 '22 05:11

Shafik Yaghmour


The C Standard allows the comparison to be true, but it is also allowed to be false (the behavior is unspecified). It depends on the compiler performing common string merging (for which gcc has an option to turn it on or off).

From the gcc 4.8.1 manual:

-fmerge-constants Attempt to merge identical constants (string constants and floating-point constants) across compilation units.

This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior. Enabled at levels -O, -O2, -O3, -Os.

-fmerge-all-constants Attempt to merge identical constants and identical variables.

So what you observe is a compiler performing string merging for the two "name" literals.

like image 30
Jens Avatar answered Nov 10 '22 04:11

Jens