Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Differentiate between int main and int main(void) function in C
In C programming, there is a subtle but important difference between int main() and int main(void). Both declare the main function to return an integer, but they differ in how they handle function parameters.
Syntax
int main() {
// Function body
return 0;
}
int main(void) {
// Function body
return 0;
}
The int main() Function
The int main() function with empty parentheses indicates that the function can accept any number of arguments. In C, when no parameters are explicitly specified, the function can be called with any number of parameters or without any parameters.
Example
Below is a C program demonstrating int main() function ?
#include <stdio.h>
int main() {
static int a = 10;
if (a--) {
printf("after decrement a = %d
", a);
main(10); // This compiles because main() can accept arguments
}
return 0;
}
after decrement a = 9 after decrement a = 8 after decrement a = 7 after decrement a = 6 after decrement a = 5 after decrement a = 4 after decrement a = 3 after decrement a = 2 after decrement a = 1 after decrement a = 0
The int main(void) Function
The int main(void) function explicitly indicates that it takes no arguments. The void keyword makes it clear that the function cannot be called with any parameters.
Example
This C program uses int main(void) function ?
#include <stdio.h>
int main(void) {
static int a = 10;
if (a--) {
printf("after decrement a = %d
", a);
main(); // No arguments allowed with void
}
return 0;
}
after decrement a = 9 after decrement a = 8 after decrement a = 7 after decrement a = 6 after decrement a = 5 after decrement a = 4 after decrement a = 3 after decrement a = 2 after decrement a = 1 after decrement a = 0
Key Differences
| Feature | int main() | int main(void) |
|---|---|---|
| Parameter specification | Can accept any number of arguments | Explicitly takes no arguments |
| Function calls | main(10) compiles successfully | main(10) causes compilation error |
| Type safety | Less strict | More strict and explicit |
Best Practice
Using int main(void) is considered better practice as it makes the function signature explicit and prevents accidental function calls with arguments.
Conclusion
While both int main() and int main(void) work for basic programs, int main(void) provides better type safety by explicitly stating that no arguments are accepted. This prevents potential errors and makes the code more readable.
