c++arraysstringgcc6

Is this valid C++ code? This doesn't work how it supposed to be


int main() {
    
    string str[5] = "ABCD";
    std::cout << str[3] << std::endl;
    std::cout << str[0] << std::endl;
    return 0;
}

This code prints:

ABCD

ABCD

I didn't get it, how str[3] prints ABCD?

Compiler: GCC 6.3


Solution

  • The code is not valid C++ code and it shouldn't compile. And it doesn't with clang and gcc version above 7. It is most likely a bug in older version of gcc that got fixed in version 7.

    std::string str[5]
    

    What you have here is a C array of 5 elements of std::string. This is how you would initialize it:

    std::string strings[5] = {"1st string", "2nd string", "3rd string", "4th string", "5th string"};
    

    In this case strings[0] would be "1st string" and strings[3] would be "4th string".

    However don't do this. Don't use C arrays in C++. Use std::vector or std::array if you need an array of strings: std::array<std::string> strings or std::vector<std::string> strings.

    That being said, I suspect that you want just one string, aka:

    std::string str = "ABCD";
    

    In this case str[0] is 'A' and str[3] is 'D'