Click here to Skip to main content
15,915,093 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
(void *) "bar" == (void *) &"bar"


Is the equality true in all versions of the ISO C Standard?

What does the ISO C Standard say about this?

What I have tried:

The equality is true using gcc and the following standards: c89, c90, c99, c11, c17, c2x.
Posted
Updated 21-Mar-20 16:52pm
Comments
CPallini 20-Mar-20 9:36am    
The standard say: "You, BAD BAD BAD guy!" :-)

Quote:
Is the equality true in all versions of the ISO C Standard?

Yes.
The address of the first character of a string constant is a pointer to the string itself, and the name of an array is a pointer to the first element of that array.
Since a string is an array of characters, "bar" is a pointer to the first character in the string, and the address of the string is also a pointer to the first character. The two evaluate to the same address, so the two pointers are identical.

This will be the same in all versions of C, even though it looks like it should be wrong!
 
Share this answer
 
Comments
Richard MacCutchan 20-Mar-20 8:35am    
Except that the second one is the address of the pointer.
OriginalGriff 20-Mar-20 8:52am    
No, because it's a constant string - and the address of the string is a pointer to the first element in the string rather than the address of a pointer to the first element. Since it's a constant, the address isn't stored in memory, it's a constant item.
I did say it looks wrong! :laugh:
Richard MacCutchan 20-Mar-20 8:54am    
Run the code.
OriginalGriff 20-Mar-20 9:07am    
I did:
int main()
{
    printf("Hello World\n");
    if ((void *) "bar" == (void *) &"bar")
        printf("Same\n");
    else
        printf("different\n");
    return 0;
}


https://www.onlinegdb.com/online_c_compiler

Result:

Hello World
Same
OriginalGriff 20-Mar-20 9:09am    
It'll be different if your compiler isn't automatically optimising string constants (I think it's the -O option that disables that, but it been a very long time and I could be wrong), but that's usually on by default.
Quote:
What does the ISO C Standard say about this?
You can find out by reading it.
 
Share this answer
 
Quote:
Is the equality true in all versions of the ISO C Standard?

I would consider that the answer can also be 'No'.
Your test compare address of both 'bar', to get the answer 'true', your compiler must have identified that both strings are the same and have optimizations activated so both strings are merged in same place in executable.
You can't expect that every version of every compiler with any combination of optimizations will always behave the same.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900