jeudi 27 juillet 2023

Why does std::cout print a string twice depending on scope? [duplicate]

When printing a string without a NULL terminator, C++ outputs the next string twice if the first one is defined outside of main(). This doesn't happen when a NULL terminator is added (next string is printed once in both cases).

#include <iostream>

int main() {
        const char message[4] = {'a', 'b', 'c', 'd'};
        std::cout << message << std::endl;
        std::cout << "Hello" << std::endl;

        return 0;
}

Output:

abcd
Hello
#include <iostream>

const char message[4] = {'a', 'b', 'c', 'd'};
int main() {
        std::cout << message << std::endl;
        std::cout << "Hello" << std::endl;

        return 0;
}

Output:

abcdHello
Hello

Aucun commentaire:

Enregistrer un commentaire