What will be the output of the given C++ code that attempts to concatenate character arrays using the + operator?

Asked In: BPSC TRE 1.0
#include <iostream>
#include <string>
using namespace std;
int main() {
    char s1[6] = "Hello";
    char s2[6] = "World";
    char s3[12] = s1 + " " + s2;
    cout << s3;
    return 0;
}
                        

Options

  • A. Hello
  • B. World
  • C. Error
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

C. Error

Detailed Explanation

Correct Answer: Option C — Error

Explanation: C-style character arrays cannot be concatenated using the + operator. The expression s1 + " " + s2 is invalid because s1 is a character array that decays to a pointer, and pointer arithmetic cannot concatenate strings. Use std::string objects with +, or use appropriate C-string functions. In valid C++ source code, string literals must use straight quotation marks.