6 Answers
6

Because 'A' is not a pointer, it's a char, 65 or 4116 if the underlying character set is ASCII.

"Stack", on the other hand, is string, basically the character array {'S', 't', 'a', 'c', 'k', '\0'}, which degrades to a pointer to its first character.

Your "difference between static_cast and ()" has been answered here, far better than I could.

The reason why you get rubbish with a char var = 'x'; cout << &var ... is because &var is a char * which means it's being treated as a string - in that case, cout outputs characters up to the final nul character \0 which isn't there, or is there beyond the character. The following code shows this:

When you uncomment the q lines, it works, because it's putting zeros around the character, outputting x on its own). Keep in mind this is not kosher C, it's only working because of the way my stack is organised. Don't use this is real code.

In this case, 'A' is just a value (probably '65'). Whenever C sees something in single quotes, it assumes it's dealing with a single character. Thus, you're essentially saying that the pointer 'letter' is going to point to whatever is at memory address 65. . . probably not what you're going for, so the compiler flags it as an error.

On the other hand, when you assign a string ("A"), the compiler does some magic behind the scenes to make it work. It takes that string and puts it somewhere into your executable, then every time you use that particular string, it substitutes the memory address of the string it knows about for the literal you've put into the program.

Also, static_cast(value) is preferred over (type)value because static_cast<>() tends to be a little more restrictive in what it'll do (so more errors are caught at compile-time). It's also more verbose (for example, there's const_cast(value) which will convert a value from a const (immutable) to something that can be modified by your code.

You've explained things pretty well, but nit-picking re "every time you use that particular string, it substitutes the memory address of the string it knows about for the literal you've put into the program": the Q only did this once to copy that address into a pointer, after which the string is used but the "magic" isn't continually involved.
–
Tony DAug 20 '10 at 7:48

One way I usually follow is to use the typeid operator to understand the types I am dealing with.

Thoug the type_info::name returns an implementation defined string, it is usually many times quiet self explanatory to understand what we are dealing with. The output below is shown when compiled with gcc