0

I've made this example to show what I'm talking about. I want to know if there is a way to run through main() without resetting value to 0.

int main(){

   int value = 0;
   value++;
   cout << value << endl;
   main();
}
  • Use static int value =0; – TUI lover Mar 24 '21 at 18:16
  • 6
    It is illegal to call `main` inside your program, so no. – NathanOliver Mar 24 '21 at 18:16
  • 2
    _...The main function has several special properties: 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively..."_ https://en.cppreference.com/w/cpp/language/main_function – Richard Critten Mar 24 '21 at 18:17
  • 1
    Don't learn C++ writing C programs. C allows recursion to `main`; [C++ does *not*](https://stackoverflow.com/questions/2128321/can-main-function-call-itself-in-c). – WhozCraig Mar 24 '21 at 18:18

2 Answers2

3

Before answering the question, your example has two big problems

  • Calling, or even taking the address of, main is not allowed.
  • Your function has infinite recursion which makes your program have undefined behavior.

A different example where value is saved between calls could look like this. It uses a static variable, initialized to 0 the first time the function is called, and is never initialized again during the program execution.

#include <iostream>

int a_function() {
    static int value = 0;
    ++value;
    if(value < 100) a_function();
    return value;
}

int main(){
    std::cout << a_function();   // prints 100
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Cheers, as I responded to a different comment, I just needed a quick example which gets the idea across, I can see that it's bugging a lot of people. Next time I'll be sure to show a correct example. – Toast258 Mar 24 '21 at 18:39
  • @Toast258 :-) Many of us jump at those things pretty quickly Cheers! – Ted Lyngmo Mar 24 '21 at 18:40
-1

If you want to keep the variable value local to the main function, you can declare it as static int value = 0;.

As has been pointed out in various comments though, recursively calling any function without an escape mechanism like you are is a bad idea. Doing it with main is a worse idea still apparently not even possible.

Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27
  • 2
    Please point out that will work for every function *except* `main`, since that's in the OP's code. It's UB to recursively call `main`. – cigien Mar 24 '21 at 18:17
  • 2
    static variables in `main` are pointless. `main` is only ever called once by the OS – NathanOliver Mar 24 '21 at 18:17
  • 1
    I wouldn't say "not even possible". I don't think many compilers would stop you. It's just not allowed because the standard says so. – Ted Lyngmo Mar 24 '21 at 18:25
  • Yes haha, I realise that it is a bad idea, however, I just needed to write a question quickly and just wrote something which would show what I'm talking about. I promise I'm not stupid. – Toast258 Mar 24 '21 at 18:26