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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With