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?
40
Upvotes
View all comments
Show parent comment
0
u/xenomachina Aug 05 '25
In Python, top-level statements are executed when the module they appear in is first loaded. In C and C++, modules aren't loaded at runtime. (At least, not normally.) So if you had a program that consisted of several modules, when would you expect the top-level code from each module to get executed?