r/computerscience • u/W_lFF • Aug 05 '25
Why do some programming languages have a "main" function and don't allow top-level statements?
Only language I've used with this design choice is C++ and while I didn't have much issues with it I still wonder why? Wouldn't that make the language more restrictive and difficult to use? What's the thought process behind making a language that requires a main function and not allowing any statements in the global scope?
37
Upvotes
View all comments
Show parent comment
13
u/jacobissimus Aug 05 '25
Just to expand— main is actually emitted as a function because there’s operating specific stuff that has to happen to create the standard entry point.
Your compiler is going to inject stuff that sets of the stack or whatever else when the process starts and then invokes main.
If you compile for a freestanding binary you don’t need a main and can do that stuff directly