为什么在代码“456”+1中,输出是“56” [英] Why in the code "456"+1, output is "56"

查看:124
本文介绍了为什么在代码“456”+1中,输出是“56”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
int main()
{
std :: cout< 25+1;
return 0;
}

我得到5作为输出。
当我使用5+ 1,输出为空;456+1输出为56。

解决方案

字符串字面量25真的是一个类型为的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 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.

这篇关于为什么在代码“456”+1中,输出是“56”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆