main() function in C
In C, main() function is the entry point of c program, It means, When a program runs, c compiler looks for main() function to execute c program, Without main(), C program cannot run. C program execution starts from main() function.
main() function returns value of type int to the Operating System to notify, weather program run successfully or terminated abnormally. It returns 0 or 1.
Return value | Description |
---|---|
0 | Program run successfully |
1 | Program terminated abnormally |
Syntax
<return_type> main()
{
// Set of statements
return value;
}
Example
int main()
{
//Statements
return 0;
}
return always comes at the end of main() function, before closing curly braces.
main() can also be used with void return type, but it is not a good programming practice.
main() is of three types on the basis of return type and argument.
- main with return value and no argument.
- main with no return value and no argument.
- main() with Command Line Arguments.
main with return value and no argument
It is recommended practice to use main() with return type, in any c program, because it notifies operating system about program execution status. only int should be, used as return type of main() function.
Example
int main(){
//Statements
return 0;
}
main with no return value and no argument
It is not a good practice, because Operating system does not knows about program execution status. void is used as return type of main() function.
Example
void main(){
//Statements
}
main() with Command Line Arguments
In C, main() can accept inputs with command line arguments. It takes two arguments
int argc | It returns the argument count or number of argument passed to main(). It is the first argument. |
char* argv[] | It is argument vector, which is a string array holds input from user. It is the second argument. |
Syntax
int main(int argc, char* argv[]) {
//Statements
return 0;
}
Example
#include <stdio.h>
int main(int argc, char* argv[]) {
// Prints the Argument count or number of arguments
printf("Argument count is argc is %d\n", argc);
// Print argument from argv
for (int i = 0; i < argc; i++) {
printf("%s \n", argv[i]);
}
return 0;
}