HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Why do we use main function in almost all the programming languages?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
whythemainallalmostlanguagesprogrammingfunctionuse

Problem

Why do we need the main function and can't we execute the code without it?
Can't we just execute our code outside the main function by making our own function?

Solution

Well, there needs to be somewhere your code starts executing(apart from the necessary initialisation and cleanup, which isn't readily visible to the programmer in the form of code).

Let's take reference to the C language, which influenced almost every other programming language. Documentation for main() in C states

Every C program coded to run in a hosted execution environment contains the definition (not the prototype) of a function named main, which is the designated start of the program.

The main function is called at program startup, after all objects with static storage duration are initialized. It is the designated entry point to a program that is executed in a hosted environment (that is, with an operating system).

Now if we are talking about assembly language, here is what an assembly code would look like

org  0x100       

    mov  dx, msg       
    mov  ah, 9         
    int  0x21         

    mov  ah, 0x4c      
    int  0x21         

    msg  db 'Where is my main() here?', 0x0d, 0x0a, '

And now python

print("No main!")


As you can see, main() isn't mandated, it's rather a specification and a convention which has been followed all along for the languages that do mention it(likes of C, C++, Java), and well, it does serve a purpose. And yes, you can have a program that doesn't start from main(), at least in C to my knowledge(gcc via nostartfiles option).


And now python

%%CODEBLOCK_1%%

As you can see, main() isn't mandated, it's rather a specification and a convention which has been followed all along for the languages that do mention it(likes of C, C++, Java), and well, it does serve a purpose. And yes, you can have a program that doesn't start from main(), at least in C to my knowledge(gcc via nostartfiles option).

Code Snippets

org  0x100       

    mov  dx, msg       
    mov  ah, 9         
    int  0x21         

    mov  ah, 0x4c      
    int  0x21         

    msg  db 'Where is my main() here?', 0x0d, 0x0a, '$'
print("No main!")

Context

StackExchange Computer Science Q#160004, answer score: 16

Revisions (0)

No revisions yet.