为什么在代码“456”+1中,输出是“56” [英] Why in the code "456"+1, output is "56"
问题描述
#include< iostream>
int main()
{
std :: cout< 25+1;
return 0;
}
我得到5作为输出。
当我使用5+ 1,输出为空;456+1输出为56。
字符串字面量25/ code>真的是一个类型为
的char数组的值
{'2','5' \\ 0'}
(你看到的两个字符和一个null终止符。)在C和C ++中,数组可以容易地衰减到指向它们的第一个元素的指针。这是在这个表达式中发生的:
25+ 1
pre>
其中
25
衰减到&25[0] / code>,或指向第一个字符的指针。添加
1
可以指向5
。
另外,
std :: ostream
,其中std :: cout
是一个实例,const char *
(注意,char *
也可以工作),假设它是一个以null结束的字符串。所以在这种情况下,它只打印5
。#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 typeconst 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. Adding1
to that gives you a pointer to5
.On top of that,
std::ostream
, of whichstd::cout
is an instance, prints aconst char*
(note thatchar*
would also work) by assuming it is a null-terminated string. So in this case, it prints only5
.这篇关于为什么在代码“456”+1中,输出是“56”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!