What is main in C
×


What is main in C

32

 Definition: main() is a predefined function in C, serving as the entry point for program execution.

 Role: It starts and ends the execution of a C program.

 Return Type: main() can have a return type of int or void.

 Parameters: Can be written with or without parameters depending on the requirement of the program.


Importance of main() Function:

 Entry Point: Operating systems call main() to execute C programs.

 Universal: It's a universally accepted keyword in C.

 User-defined: It's a user-defined function; parameters can be passed based on program requirements.

 Runtime Invocation: Code inside main() runs at runtime, not compile time.


Syntax of main() in C

int main() {
    // code here
    return 0;
}

OR

void main() {
    // code here
}

Types of main()

void main():

 Does not return any value.

 Used when no value needs to be returned.

void main() {
    // code here
}

int main():

Returns an integer value.

Should have a return 0; statement at the end.

int main() {
    // code here
    return 0;
}

int main(int argc, char *argv[]):

Accepts command-line arguments.

int main(void):

Similar to int main(), but explicitly states no parameters.

int main(void) {
    // code here
    return 0;
}

void main(void):

Does not return any value and doesn't take any arguments.

void main(void) {
    // code here
}

Examples:

Simple main() without arguments:

// Program for Simple main() without arguments
#include<stdio.h>
void main() {
    printf("C Programming");
}

Output:

C Programming

main() with nested functions:

 // Program for main() function with nested functions
#include<stdio.h> 
void fun1() {
    printf("It is a second function.");
}
int main() {
    printf("It is a main() function\n");
    fun1();
    return 0;
}

Output:

It is a main() function.
It is a second function.

 Return Value: Use return 0; or EXIT_SUCCESS to indicate successful execution.

 EXIT_FAILURE can be used for unsuccessful termination.

 Avoid void main(): Though some compilers allow void main(), it's not standard and can lead to undefined behavior.

 This overview provides a solid understanding of the main() function in C, its types, and usage.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments