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
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:
std::string s("mathworks")creates a string object.- The condition
s != '\0'attempts to compare astd::stringwith acharliteral. C++ will try implicit conversion, which fails or produces unexpected results. s++attempts to increment astd::stringobject. Theoperator++is not defined forstd::string, causing a compiler error.printf("%s", s)expects aconst char*, but receives astd::stringobject. While some compilers allow this with a warning, the main issue iss++fails first.- Result: Compiler error due to undefined
operator++forstd::string.