Updated on 2021-11-13
The main()
function in C++ is just a function and can be used like any other
function. It is only special in that it is called by the operating systems and
has the command line arguments passed to it. However, it is still possible to
call main()
while the program is running. For example, here is a program
that computes factorials by recursively calling main()
.
#include <cassert>
#include <cstdlib>
#include <iostream>
// Recursive main!
int main(int argc, char **argv) {
if (argv == nullptr) {
if (argc == 0) return 1;
return argc * main(argc - 1, nullptr);
} else {
int result = main(std::atoi(argv[1]), nullptr);
std::cout << result << std::endl;
return 0;
}
}
Copyright © 2020-2021 thestuffido.xyz All Rights Reserved