C main()
The main()
function is the entry point of every C program. It is where execution begins. The C compiler looks for the main()
function to start program execution. Every C program must have exactly one main()
function.
Importance of main()
Function
- Entry Point: Execution of a C program begins from the
main()
function. - Standard Requirement: The C standard mandates that every C program must have a
main()
function. - Return Value: The
main()
function typically returns an integer value to indicate the success or failure of the program. - Arguments: It can take command-line arguments
argc
andargv
to pass inputs from the command line.
Syntax of main()
Function
The syntax of main() function is:
</>
Copy
int main() {
// Code execution starts here
return 0;
}
Examples of main()
Function
1. Basic main()
Function
In this example, we will define a simple main()
function that prints “Hello, World!” to the console.
main.c
</>
Copy
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Explanation:
#include <stdio.h>
: The standard input-output library is included to useprintf()
.int main()
: The program execution starts from themain()
function.printf("Hello, World!\n");
: Theprintf()
function prints the text to the console.return 0;
: The program returns 0 to indicate successful execution.
Output:
Hello, World!
2. Returning an Exit Code from main()
In this example, we will return a non-zero exit code from the main()
function to indicate an error.
main.c
</>
Copy
#include <stdio.h>
int main() {
printf("Exiting with error code 1\n");
return 1; // Non-zero value indicates an error
}
Explanation:
printf("Exiting with error code 1\n");
: Prints a message indicating an error.return 1;
: Returns a non-zero exit code to signal an error.
Output:
Exiting with error code 1
3. Using main()
with Command-Line Arguments
In this example, we will modify the main()
function to accept command-line arguments and print them.
main.c
</>
Copy
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Explanation:
int argc, char *argv[]
: Themain()
function accepts command-line arguments.printf("Number of arguments: %d\n", argc);
: Prints the number of command-line arguments.for (int i = 0; i < argc; i++)
: Iterates through all the arguments.printf("Argument %d: %s\n", i, argv[i]);
: Prints each argument passed to the program.
Output (Example Run in Terminal):
$ ./a.out Hello World
Number of arguments: 3
Argument 0: ./a.out
Argument 1: Hello
Argument 2: World
Conclusion
In this tutorial, we covered the main()
function in C:
- We covered the importance of the
main()
function as the entry point of a C program. - We demonstrated a simple
main()
function printing “Hello, World!”. - We showed how
main()
can return an exit code. - We implemented
main()
with command-line arguments.