#include <iostream>
int main()
{
std::cout << "25"+1;
return 0;
}
I am getting "5" as output. when I use "5"+1,output is blank;"456"+1 output is "56". confused what is going behind the scenes.
#include <iostream>
int main()
{
std::cout << "25"+1;
return 0;
}
I am getting "5" as output. when I use "5"+1,output is blank;"456"+1 output is "56". confused what is going behind the scenes.
The string literal "25"
is really a char array of type const char[3]
with values {'2', '5', '\0'}
(the two characters you see and a null-terminator.) In C and C++, arrays can easily decay to pointers to their first element. This is what happens in this expression:
"25" + 1
where "25"
decays to &"25"[0]
, or a pointer to the first character. Adding 1
to that gives you a pointer to 5
.
On top of that, std::ostream
, of which std::cout
is an instance, prints a const char*
(note that char*
would also work) by assuming it is a null-terminated string. So in this case, it prints only 5
.
Behind the scenes, "25"
is an array of three characters: two representing '2'
and '5'
, and a terminator with the value of zero to mark the end.
An array is a slightly strange creature, with a tendency to change into a pointer (to the first element) if you do anything with it. That's what's happening here: adding one to an array doesn't make sense, so it turns into a pointer. Adding one to that gives a pointer to the second character.
When given a pointer to a character, <<
assumes it points to a terminated string, and keeps printing characters until it finds a terminator (or explodes in some way, if there isn't one). So giving it a pointer to the second character of a string will print all the characters from the second onwards, as you observed.
If you're new to C and C++, you should first decide which language to learn first, since they're very different. If you choose C++, you'd be wise to become familiar with its friendly, high-level library (such as std::string
for dealing with strings without this kind of weirdness) before plunging into the low-level madness of arrays and pointers.
When you write a "", the compiler understands you are putting a string inside. In this case, you are using the function cout, so it prints on screen this string. You are operating with strings when you use the '+' operator, so you are doing a displacement operation before send it to the cout.