r/computerscience • • 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

74 comments sorted by

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

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.

0

u/istarian Aug 06 '25

The parameters still have to come from somewhere, though.

1

u/finn-the-rabbit Aug 08 '25 edited Aug 08 '25

Your compiler is going to inject stuff

Just adding my anecdote because that reminded me of something.

When I dicked around with assembly, I was stuck for a while because my code didn't print. IIRC, I dug around, dumped a binary of a C equivalent, and I'm pretty sure I saw an entry point for main() actually, which was funny to me, like a main() of main(). I dug further and I think I saw code where the compiler does all that OS specific stuff in before explicitly calling main(). And surely enough, there was a flush some time after main() returns. When I inserted a call to flush in my assembly code, things worked as expected so that was an interesting learning experience.