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
4
u/Roflkopt3r Aug 05 '25
Yeah, it is just 'syntactic sugar' in a sense.
But 'injecting stuff' also connects to another reason to have a main: Because it explicitly defines the launch arguments.
This also is not strictly necessary, but many programming paradigms want to avoid the use of undeclared variables. C++ has the parameters argc (argument cont) and argv (arguments as a string array with n=argc elements) for main(), so it is easy to see when a program accesses its launch parameters. Whereas in programs without a main function, access to those parameters can be quite confusing to readers.
Obviously there are other ways to resolve that confusion, like accessing them via well known standard library functions, but having an explicit declaration for them is a solid solution.