On Tue, 16 Jan 2007 12:27:24 -0600, "Michael Goldshteyn"
<> wrote in comp.lang.c++:
> Consider the following two lines of code, the first intended to print "Hello
> world\n" and the second intended to print the character 'P' to stdout.
>
> ---
> std::cout << static_cast<std:
stringstream &>(std:
stringstream() <<
> "Hello world\n").str();
>
> std::cout << static_cast<std:
stringstream &>(std:
stringstream() <<
> 'P').str();
> ---
>
> Instead, the first line print the address of the string literal "Hello
> world\n" and the second prints the ASCII value of 'P', 80.
>
> I would like a meaningful discussion as to why this is happening. It appears
What do you consider to be a meaningful discussion? How about the
fact that the code does exactly what it is supposed to do, according
to the C++ standard, and your expectations are wrong?
> that in the first case, the const char * that is the string literal is being
> interpreted in void * context and in the second case, the character is
> somehow being interpreted as an int.
The insertion operator (<<) for streams is overloaded for all the
built-in types. Its purpose is to generate text streams, so for all
integer and floating point arithmetic types it performs a numeric
value to text conversion and inserts the text into the stream.
Type char is a character type, so this numeric value to text
conversion is performed, exactly as the standard requires it to be. In
your character set, probably ASCII, the numeric value of 'P' is 80.
There is a special overload for pointer to character types. This
overload is based on the assumption that they are pointing to C style
strings (arrays of characters terminated by a '\0' character). Such
strings are already text, so no conversion is necessary, the C string
is merely inserted into the stream as-is.
On the relatively rare occasions when you actually what to output a
text representation of the address contained in a pointer to char,
rather than the C string it is assumed to point to, you merely cast it
to pointer to void, which has no such overload.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html