main function

Jun 14, 2013 at 2:23pm
Can we call main() function ???
Jun 14, 2013 at 2:25pm
I think it's undefined behaviour - which, in other words, means no. I'm sure a Google search will find you an authoritative answer quickly.
Jun 14, 2013 at 2:27pm
Nor should you ever need to. The purpose of a main function is to serve as an entry point to your program, so you'll inherently enter it when you program starts.

Any other flow control should use the appropriate methods; loops, ifs and the like.
Jun 14, 2013 at 2:37pm
Incidentally, it's one of the differences between C and C++: in C, main() can be called from within a program, in C++ this is not allowed.
Jun 14, 2013 at 3:00pm
@Cubbi, is that in the spec? AFAIK, there is nothing magical about main(). If you want to call it, you can, but if you are, I'd rethink your design since this is not generally useful.
Jun 14, 2013 at 3:17pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

// The name main is not otherwise reserved. (there is nothing magical about main)
namespace A
{
    void main( double d ) { std::cout << "A::main(" << d << ")\n" ; }
    int main() { std::cout << "A::main()\n" ; }
}

// A program shall contain a global function called main,
// which is the designated start of the program - IS.
int main()
{
    A::main(23.4) ;
    A::main() ;

    // The (global) function main shall not be used within a program - IS.
    // (if you want to call it, you can) a conforming compiler would give an error if you do.

    main() ; // error: ISO C++ forbids taking address of function '::main' [-Wpedantic]
}
Topic archived. No new replies allowed.