简体   繁体   中英

Calling main inside of main in c

I'd like to ask why when I have:

int main() {
    printf( "Hello world") ;
    main ;
}

the compiler prints "Hello world", but when I have main() instead of main, it prints repeatedly "Hello world".

int main() {
    printf( "Hello world") ;
    main ;
}

The last statement main ; has virtually no meaning: it just take the function designator, have it converted to a pointer pointing at the function, then throw the result away.

int main() {
    printf( "Hello world") ;
    main() ;
}

This code uses "main-recursion". The function main() is called inside main() . This recursive call will continue infinitely, and it may crash somewhere when the stack ran out or it may go until you stop by Ctrl+C or something if the compiler is smart enough to convert this tail recursion into a simple loop.

main(); will call the function recursively (and eventually crash due to a stack overflow, unless your compiler has cleverly optimised the recursion out to a loop).

main is an expression with a value equal to the address of the function main() . It's a no-op but nonetheless syntactically valid.

(Note that the behaviour of calling main from itself is undefined in C++, but is valid in C. Omitting the return value from main is also well-defined in C: 0 is assumed).

This is because:

main()

is a method call. You are recursively calling the main function repeatedly. This will run until the call stack overflows.

main

Is a function pointer, so you're not really doing much on this line. The function exits after printing "Hello World" once.

main is a function pointer whereas main() is function call.

When you write main it's just a statement , you are not using it or modifying it anywhere but main() is function call which will be a recursive (infinite in this case) call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM