How does the following print?:
#include <iostream.h>
#include <string.h>
void main()
{
char s[50];
strcpy (s, "What ");
strcat (s, "does this " );
strcat (s, "do?");
cout << s << endl;
}

Can you explain?

Dani AI

Generated

Short answer: the three string operations produce the single output

What does this do?

As showed, the code builds that sentence by copying the first literal into a buffer and then appending two more literals. correctly pointed out modern compilers will complain about old headers/usage, and was right to flag the header choice.

How it works (quick, concrete facts)

  • strcpy copies bytes from the source into the destination including the terminating NUL byte. strcat scans the destination to the terminating NUL, then copies the characters from the source and writes a final NUL. See strcpy and strcat.
  • Both require the destination buffer to be large enough. If it is not, the behavior is undefined (buffer overflow). Repeated strcat calls also re-scan the already-built string each time, which is wasteful for many concatenations.

Safer, practical advice

  • Prefer std::string for concatenation: it manages memory, is readable, and avoids many common errors (std::string).
  • If you must use C APIs, use functions that limit writes and carefully track remaining space; test with sanitizers (-fsanitize=address,undefined) or valgrind to catch overruns.
  • Use a proper main signature and up-to-date headers; see the standard rules for main (main function rules).

These points expand on the replies already in the thread and focus on the real risks (undefined behavior and inefficiency) and practical, modern fixes.

Recommended Answers

All 2 Replies

All it prints is a compiler error and some warnings when compiled using GCC.

Correct code is:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  char s[50];
  strcpy (s, "What ");
  strcat (s, "does this " );
  strcat (s, "do?");
  cout << s << endl;
  return 0;
}

which prints exactly what you'd expect it would...

The C-style string handling functions are declared in <cstring>, not <string>.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.