163k views
1 vote
Any problems with this code?

string s = "chimp";
s[2] = 'u';
A) No, it will replace the character 'i' with 'u'
B) Yes, it will throw an exception
C) Yes, strings cannot be modified in C++
D) No, it will compile and run successfully

1 Answer

4 votes

Final answer:

The code provided has a problem because in C++, strings objects cannot be modified using array indexing. Standard strings are immutable, and modifying them without proper functions will result in undefined behavior.

Step-by-step explanation:

The student has asked about the correctness of a code snippet in C++. The question is whether the following code has any problems:

string s = "chimp"; s[2] = 'u';

The correct answer is C) Yes, strings cannot be modified in C++. In C++, the std::string class represents a sequence of characters and the objects of this class are immutable, meaning that once a string object has been created, it cannot be modified. Attempts to modify a string literal directly through its character elements, like in the code provided, will result in undefined behavior. To modify a string, you should use methods provided by the std::string class, such as replace() or insert().

Therefore, the appropriate choice for the student's question is that there is indeed a problem with this code because standard strings in C++ are not designed to be mutable in this manner.

User Igor Azevedo
by
8.1k points