user1299661
user1299661

Reputation: 193

Calling the main function in C++ is ignored using CodeBlocks

Possible Duplicate:
Can main function call itself in C++?

I decided to do a small test using CodeBlock IDE by calling the main function which should be an illegal act.

EX:

#include <iostream>
using namespace std;

int main()
{
  cout<<"hello"<<endl;
  main();
  return 0;
}

Strangely, in code blocks I was able to compile this mess. Does anyone know why?

Output: hello

Upvotes: 4

Views: 947

Answers (3)

Sad Al Abdullah
Sad Al Abdullah

Reputation: 379

You can call any function under main function.main is also a function which is trigger in runtime by complier. Yes it is illegal act but you can call main function under main.To call main function under main cause recessive and run infinitely time. In VS2008 you will get a warning to call main function but the program runs without any problem .

Upvotes: 0

Prahlad Yeri
Prahlad Yeri

Reputation: 3663

cout<<"hello"<<endl;
**main();**
return 0;

The second line main() will cause an infinite recursive loop with the main() function calling itself again and again, this in turn will cause no path in your code return value.

Since not all paths are returning values, no C compiler will compile this. Forget C, even C# compiler halts when it finds that all paths are not returning a value, though the code is legible.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361692

As you said in your question itself that calling main() explicitly from your code is forbidden by the language specification. Only the runtime can call it.

As you use GCC to compile your code (read your comment), the -pedantic option would give you appropriate diagnostic in the form of error or warning. So try this:

g++ program.cpp -pedantic

Upvotes: 9

Related Questions