Why in the code “456”+1, output is “56”
Question:
#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.
Answer:
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" + 1where "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.
想要看到更多学习笔记、考试复习资料、面试准备资料?
想要看到IBM工作时期的技术积累和国外初创公司的经验总结?
敬请关注:
[CSDN](https://blog.csdn.net/u013152895)
[简书](https://www.jianshu.com/u/594a3de3852d)
[博客园](https://www.cnblogs.com/vigorz/)
[51Testing](http://www.51testing.com/?15263728)

浙公网安备 33010602011771号