OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

24.

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

24. (C++ Question) String printer

What would be the output of the following code?

#include <iostream>

int main(){
    std::string s("mathworks");
    for(;s!='\0';s++)
        printf("%s", s);
}

Pick ONE option

Choose one option.
Show answer & explanation
Answer: C. Compiler error

The code has a type mismatch: s is a std::string object, but the loop condition compares it with '\0' (a char). The ++ operator increments the entire string object, not individual characters, which is invalid. Additionally, printf("%s", s) passes a std::string object where a C-string pointer is expected, requiring an implicit conversion that printf doesn't support. Modern compilers will flag these errors.

Step-by-step Derivation:

  1. std::string s("mathworks") creates a string object.
  2. The condition s != '\0' attempts to compare a std::string with a char literal. C++ will try implicit conversion, which fails or produces unexpected results.
  3. s++ attempts to increment a std::string object. The operator++ is not defined for std::string, causing a compiler error.
  4. printf("%s", s) expects a const char*, but receives a std::string object. While some compilers allow this with a warning, the main issue is s++ fails first.
  5. Result: Compiler error due to undefined operator++ for std::string.