String address and string content

B

bintom

char str1[ ] = "abc", str2[ ] = "abc";

if(str1 == str2)
cout << "Identical";
else
cout << "Different";

I ran the above code on Dev C++ and the output was "Different" as
expected. In other words, the compiler compared the location of str1
and str2 in memory. But in, in the statement

cout << str1;

why does it return the string at str1 and not the memory address of
str1?

What is the technical jargon for this dual behaviour?

Thanks,
Bintom
 
P

Paul N

char str1[ ] = "abc", str2[ ] = "abc";

if(str1 == str2)
  cout << "Identical";
else
  cout << "Different";

I ran the above code on Dev C++ and the output was "Different" as
expected. In other words, the compiler compared the location of str1
and str2 in memory. But in, in the statement

   cout << str1;

 why does it return the string at str1 and not the memory address of
str1?

What is the technical jargon for this dual behaviour?

The word you're looking for may be "overloading". The << operatior on
cout is overloaded, in that it does different things depending on the
type of the things sent to it. So a void pointer causes it to print
the address, whereas a char pointer causes it to print a string.

The fact that you are surprised at this suggests you're either not
entirely clear what's going on, or you haven't thought it though
properly. Presumably you were expecting

cout << "Different";

to print a string, rather than the address where the text is stored?
It's a char pointer too...

Hope that helps.
Paul.
 
S

SG

[...] Presumably you were expecting

cout << "Different";

to print a string, rather than the address where the
text is stored? It's a char pointer too...

That depends on what you consider to be "it". The string literal is
certainly an lvalue expression of type const char[10]. But it
implicitly converts to a const char* (in this case) which is then
passed to one of the overloads for operator<<.

Cheers!
SG
 
R

Rolf Magnus

SG said:
[...] Presumably you were expecting

cout << "Different";

to print a string, rather than the address where the
text is stored? It's a char pointer too...

That depends on what you consider to be "it". The string literal is
certainly an lvalue expression of type const char[10]. But it
implicitly converts to a const char* (in this case) which is then
passed to one of the overloads for operator<<.

Same goes for the comparison of str1 and str2.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top