Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

abnormal behaviour in cout. It is printing twice character array after declaration of another same valued character array

So I was writing the code to print a character array in c++. The normal code is:-

#include <iostream>
using namespace std;

int main()
{
    char X[5] = {'A', 'B', 'C', 'D', 'E'};
    cout << X << endl;
    return 0;
}

and it’s printing:-ABCDE as expected but I tried to create another character array like this

#include <iostream>
using namespace std;

int main()
{
    char X[5] = {'A', 'B', 'C', 'D', 'E'};
    char Y[5] = {'A', 'B', 'C', 'D', 'E'};
    cout << X << endl;
    return 0;
}

and I thought that I’ll get same output but it didn’t happend.
the output was ABCDEABCDE I didn’t understood why it happened.
At that time I was coding in my computer. So, I visited online c++ compiler and still got the same result.
Please anyone help me to understood why it happened?
I am using C++14 in my computer.
This is the link of online compiler website on which I rechecked my code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The behaviour is undefined.

std::ostream‘s overload for a const char* (selected due to pointer decay), doesn’t stop outputting until NUL is reached.

So including NUL terminators in both arrays is the fix:

char X[/*let the compiler do the counting*/] = {'A', 'B', 'C', 'D', 'E', 0};

&c.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading