6

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?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
OldSchool
  • 2,123
  • 4
  • 23
  • 45

4 Answers4

7

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.

ajay
  • 9,402
  • 8
  • 44
  • 71
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
2

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.

Jens
  • 69,818
  • 15
  • 125
  • 179
1

String literals are nothing memory references hence when you do char *p="name"; this, it means nothing but:

     |n |a |m | e
    /
   p

p points to first character of the string literal. So doing this:

p=="name" evaluates to someAddress==someAddress. However this behavior is unspecified.

Sadique
  • 22,572
  • 7
  • 65
  • 91
1

Ok, let's disect what this does.

p is a pointer to name\0. So, here you are comparing p (a pointer) to "name" (also a pointer). Well, the only way this will every be true is if somewhere you have p="name" and even then, "name" is not guaranteed to point to the same place everywhere.

I believe what you are actually looking for is either strcmp to compare the entire string or your wanting to do if (*p == 'n') to compare the first character of the p string to the n character

You want to use strcmp() == 0 to compare strings instead of a simple ==, which will just compare if the pointers are the same.

The expression strcmp( p, "name") == 0 will check if the contents of the two strings are the same.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51