Weird output of ""+'b'

Hello,

I wrote the following line in c++:
cout << ""+'b' << endl;

The output is '[', which is quite weird. Can anyone help to explain the output? Thanks!
Can anyone help to explain the output?


"" <= pointer
'b' <= char (which is a sort of integer)

Adding pointer and integer together results in a new address (via pointer arithmetic,) which you have no business accessing, leading to undefined behavior.
Thanks for the reply!

Let's see you have a sentence:
cout << 1+'b' <<endl;

But why "" is a pointer, while the 1 here is not a pointer?
A string literal is actually const character array with a null terminating character.

const char string[] = "Hello"; // this compiles

As you know, arrays are closely related to pointers.

This:

std::cout << 1 + 'b' << std::endl

1 is an integer literal and 'b' is sort of an integer so together you get an integer (99). 'b' is 98. 98 + 1 = 99.

std::cout << static_cast<char>(1 + 'b') << std::endl

You get 'c'.
Last edited on
Topic archived. No new replies allowed.