Why does cout print “2 + 3 = 15” in this snippet of code?

后端 未结 5 783
暗喜
暗喜 2020-12-07 16:15

Why is the output of the below program what it is?

#include 
using namespace std;

int main(){

    cout << \"2+3 = \" <<
    cou         


        
5条回答
  •  不思量自难忘°
    2020-12-07 16:38

    You can easily debug your code this way. When you use cout your output is buffered so you can analyse it like this:

    Imagine first occurence of cout represents the buffer and operator << represents appending to the end of the buffer. Result of operator << is output stream, in your case cout. You start from:

    cout << "2+3 = " << cout << 2 + 3 << endl;

    After applying the above stated rules you get a set of actions like this:

    buffer.append("2+3 = ").append(cout).append(2 + 3).append(endl);

    As I said before the result of buffer.append() is buffer. At the begining your buffer is empty and you have the following statement to process:

    statement: buffer.append("2+3 = ").append(cout).append(2 + 3).append(endl);

    buffer: empty

    First you have buffer.append("2+3 = ") which puts the given string directly into the buffer and becomes buffer. Now your state looks like this:

    statement: buffer.append(cout).append(2 + 3).append(endl);

    buffer: 2+3 = 

    After that you continue to analyze your statement and you come across cout as argument to append to the end of buffer. The cout is treated as 1 so you will append 1 to the end of your buffer. Now you are in this state:

    statement: buffer.append(2 + 3).append(endl);

    buffer: 2+3 = 1

    Next thing you have in buffer is 2 + 3 and since addition has higher precedence than output operator you will first add these two numbers and then you will put the result in buffer. After that you get:

    statement: buffer.append(endl);

    buffer: 2+3 = 15

    Finally you add value of endl to the end of the buffer and you have:

    statement:

    buffer: 2+3 = 15\n

    After this process the characters from the buffer are printed from the buffer to standard output one by one. So the result of your code is 2+3 = 15. If you look at this you get additional 1 from cout you tried to print. By removing << cout from your statement you will get the desired output.

提交回复
热议问题