Barry Schwarz <
schw...@dqel.com> writes:
> On 12 Oct 2014 17:26:40 GMT, arnuld <sun...@invalid.address> wrote:
>
> >#include <iostream>
> >
> >int main()
> >{
> > int arr1[] = {10,11,12};
> > char arr2[] = {'a','b','c'};
> > double arr3[] = {0,10, 0.11, 0.12};
> > const char* str = "comp.lang.c++";
> > const wchar_t* alpha = L"first line"
> > "Second Line";
> >
> > std::cout << "arr1 = " << arr1 << std::endl;
> > std::cout << "arr2 = " << arr2 << std::endl;
> > std::cout << "arr3 = " << arr3 << std::endl;
> > std::cout << "str = " << str << std::endl;
> > std::wcout << "alpha = " << alpha << std::endl;
> >
> > return 0;
> >}
> >An array name is converted to pointer to its first element. arr1 and arr3
> >(1st and 3rd wariable) are arrays of int and float respectively and they
> >behave accordingly to this rule but arr2 and str (2nd and 4th variables)
> >do not. Why ?
>
> Actually they do. The difference is how the compiler generates code
> for the overloaded operator <<. When the right operand has type
> pointer to char, the generated code treats the address as the start of
> a C style string (similar to using %s in printf). When the operand
> has type pointer to "object that cannot be a string," the generated
> code treats it the same as using %p in printf.
Actually, the difference is in the definition of the operator<<()
functions involved. In all cases the array is converted to the
pointer of it's first element, i.e. this code calls
std::ostream::operator<<(int *);
std::operator<<(std::ostream &, char *)
std::ostream::operator<<(double *);
std::operator<<(std::ostream &, const char *)
std::operator<<(std::wostream &, const wchar_t *)
The operators for int* and double* simply print the address in hex,
since they cannot know the size of the array. The operator function
don't even know that an array is given as argument, they only get a
pointer. The operator<< for char* and wchar_t* also don't the size of
the array, but they rely on the programmer to pass a pointer a
null-terminated string of char's or wchar_t's, respectively. The
print all characters up to (but not including) the first null.
BTW, the GNU implementation has
std::operator<<(std::ostream &, char *)
std::operator<<(std::wostream &, wchar_t *)
which print the characters, and it also has
std::ostream::operator<<(char *);
std::wostream::operator<<(wchar_t *);
which print the pointer value in hex. But I don't know the rules
which decide between two when you write
cout << arr2;
I assume the member function is via template and the other operators
or more specific so they are chosen. But I haven't checked in the
header files.
urs