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?

40 Upvotes

74 comments sorted by

View all comments

Show parent comment

-2

u/[deleted] Aug 05 '25

The answer is in my last sentence. imports are resolved in order from top to bottom, and they are deduplicated, so that subsequent imports of the same module do not re-run.

1

u/xenomachina Aug 05 '25

I know how it works in Python. I'm asking how it would work in C and C++ if they allowed top-level statements.

-1

u/[deleted] Aug 05 '25

I don't see why it would have to work any differently. It's just a matter of the compiler emitting a flag for whether a given module has been "imported," and then running the top-level code for that module upon first import.

2

u/xenomachina Aug 05 '25

and then running the top-level code for that module upon first import.

What is "first import" in C or C++?

0

u/[deleted] Aug 06 '25

If this feature were to be implemented, it would obviously be evaluated in lexical order, just like in Python or JS.

3

u/Miserable_Guess_1266 Aug 06 '25

What's the lexical order between multiple cpp files linked into the same executable or library? Or between multiple library linked into your executable?

This boils down to the same problem as the static initialization order fiasco.

1

u/[deleted] Aug 07 '25

There's clearly an unambiguous order defined as a depth-first traversal with caching. That is in fact how Python does it. There's no barrier to implementing this scheme in code generation of the synthetic main function generated from the top-level code of the depth-first traversal of the hypothetical alternative-syntax C++ modules.