0

For instance,

const char str[] ={'H','e','l','l','o', '\0'};
const int nums[] = {1,2,3,4,5};
cout << str << " " << nums;

gives:

Hello 0x7ffff85c0cf5

Obviously, if I wanted to get addresses of both, I could do

cout << &str << " " << nums

But I'm wondering why there's a difference between this array of integers and an array of characters (string literal). Is this a special case preserved only for strings?

gust
  • 878
  • 9
  • 23
  • 1
    Note that your code has UB, because the character array is not 0-terminated. – Angew is no longer proud of SO Sep 05 '19 at 08:24
  • Edited, and will close once 10 minutes mark pass – gust Sep 05 '19 at 08:26
  • 2
    Be careful about your wording. An array itself does not _return_ anything. You pass it as an argument to `operator<<` and its different overloads are then chosen in both cases (as explained in the answers). – Daniel Langr Sep 05 '19 at 08:33
  • 1
    @DanielLangr note that not all overloads of `operator<<` are members of the `ostream` class. Many are not. In this case, the `void*` overload is, the `char*` overload is not – Remy Lebeau Sep 05 '19 at 08:37
  • @RemyLebeau I realized that a second after I posted my comment. Edited then. Thanks for pointing that out :) – Daniel Langr Sep 05 '19 at 08:37

2 Answers2

7

Yes you're absolutely correct. The << operator on ostream has a special overload for a const char*.

There's no such overload provided for an int* - in that case the const void* overload is picked.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

There is an overloaded operator<< for const char*, which your const char[] array decays to. This overload treats the char data as a null-terminated string, printing out characters until a null character is reached. However, your char[] array does not have a null terminator in it. You are lucky you are seeing only Hello and not extra garbage, or crashing the app. Your code has undefined behavior because of this.

There is no overload of operator<< for a const int[] array. Your array decays to const int*, which is handled by the operator<< overload that takes a const void* as input, which prints out the address being pointed at.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770