Main Function Header
In C, we have a special function called main
.
This function is the entry point for any C program.
In other words, when executed, our program starts from this function1.
The function has a prototype int main(void)
.
A function prototype simply states its return type, name and parameter types.
In the case of main function:
- Return type:
int
- Name:
main
- Parameter types:
void
(i.e., accepts no parameters)
While there are other forms such as int main()
, our convention is to use int main(void)
.
The type void
is similar to the None
type in Python.
Unfortunately, there is no easy comparison in JavaScript.
The closest comparison in JavaScript is the undefined
value.
Since the return type is int
, the statement return 0;
is important.
This indicates to the operating system that the program has terminated successfully.
A non-zero return value indicates that the program may have encountered an error and the value can be used to specify what error it has encountered.
Luckily, most compilers are smart enough to add return 0;
if we forgot to add.
Void
void
is a special type in C.
A function with a parameter type void
should not be called with any argument.
A function with a return type void
cannot be used as the right-hand side of an assignment.
For instance, if a function is defined such that the prototype is int f(void) { ... }
, then calling it with f(0);
gives us a compile error.
This function can only be called with f();
.
On the other hand, if a function is defined such that the prototype is void f(int x) { ... }
, then calling it with f(1);
is fine while calling it with f();
gives us a compile error.
However, if we try to assign the result back to a variable such as x = f(1);
then we get a compile error.
So in this aspect, void
is not the same as None
(Python) or undefined
(JavaScript).
However, it is still "similar" in a sense that a function that does not return anything will return void
(in C), None
(in Python) and undefined
(in JavaScript).
No Return
void | |
---|---|
1 2 3 |
|
None | |
---|---|
1 2 |
|
undefined | |
---|---|
1 2 3 |
|
-
Before calling the main, there are other steps to setup the program environment. This is usually called the startup code. ↩