1

I have got a homework where I should do some action again and again till I write "stop" in console, BUT I can't use for, while, goto, switch, [], typedef in all my code. So how can I replace the loop?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

3 Answers3

11

Recursion may be used. This example repeats what you enter until you type "stop" as an example:

#include <iostream>
#include <string>

void do_it()
{
  std::string s;
  std::cin >> s;
  if (s == "stop")
    return;
  std::cout << s << '\n';
  do_it();
}

int main()
{
  do_it();
  return 0;
}

It may not be the case here but recursion has its drawbacks. For one thing it is slower than a simple loop because in languages like C++, function call is relatively expensive. And it might cause stack overflow if it recurs too many times. Having said that, recursive version of the function can sometimes be cleaner and easier to read/understand. You can learn more about pros and cons of recursion here.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
2

As noted in comments by Jesper Juhl, they banned goto but forgot to ban setjmp/longjmp!

Unlike recursion-based solutions, setjmp/longjmp can't possibly cause a stack overflow if you iterate too many times.

#include <csetjmp>
#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::jmp_buf jump_buffer;
    setjmp(jump_buffer);

    std::cin >> s;

    if (s == "stop")
        return 0;

    std::cout << s << '\n';
    std::longjmp(jump_buffer, 0);
}

Note that longjmp is potentially dangeruous, since it doesn't call destructors. Because of that it should be avoided when possible.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
1

Challenge accepted -- C version for the original tag

#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
    if (strcmp(*argv, "stop")) {
        char *in = malloc(99);       // assume it worked
        fgets(in, 99, stdin);        // assume it worked
        *(in+strcspn(in, "\n")) = 0; // remove trailing ENTER
        main(argc + 1, &in);         // memory leak
    } else {
        printf("Stopped after %d entries.\n", argc - 1);
    }
}

See code running at ideone: https://ideone.com/Slx4g9

pmg
  • 106,608
  • 13
  • 126
  • 198