Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: May 18, 2024
Difficulty: Easy

What is Main Function in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In C programming, the main() function is the starting point of every program. It is a special function that tells the compiler where to begin executing the code. The main() function is essential because without it, the program won't know where to start running. 

What is Main Function in C

In this article, we will learn the syntax, important points, and different types of the main() function in C.

Syntax of C main() Function

In C programming, the way you write the main() function can vary, but it typically looks something like this: either int main() or int main(int argc, char *argv[]). Here's what you need to know about each part:

  1. int: This part says that the main() function will give back a number. In most C programs, returning 0 means everything went as planned, while any other number can signal that something went wrong.
     
  2. main: This is the name of the function where all C programs start running. It's like the entry point of a building – the place where you begin.
     
  3. () or (int argc, char *argv[]): These are like containers that might hold information. In simpler main() functions, it's empty. In more complex ones, it holds data that can tell the program more about how it was started, like what commands were typed to run it.
     

Here is a simple example of what the main() function might look like in a basic C program:

  • C

C

#include <stdio.h>

int main() {

   printf("Hello, world!\n");

   return 0;

}

Output

"Hello, world!


In this example, printf is a function used to print out a message, and return 0; tells the system that the program finished successfully.

Now, if you want to get a bit more advanced and pass information into your program from the outside, like from a command line, the main() function can also be written to accept arguments:

  • C

C

#include <stdio.h>

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

   printf("You ran this program with %d arguments.\n", argc - 1);

   for(int i = 1; i < argc; i++) {

       printf("Argument %d: %s\n", i, argv[i]);

   }

   return 0;

}

Output

You ran this program with 0 arguments.


In this version, argc counts how many arguments you gave, and argv is a list of those arguments as strings. The program then uses a loop to print each one out.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Important Points about C main() Function

  1. Where Execution Begins: The main() function is always the starting point of your program. This is where your computer begins to execute your code.
     
  2. Returning a Value: The main() function usually returns an integer to the operating system. A return value of 0 typically means the program ran successfully without any errors. If your program encounters issues or needs to signal something went wrong, you might return a different number.
     
  3. Standard Form: Although you can sometimes see variations, the most common way to write this function is either as int main() or int main(int argc, char *argv[]). The first one is simpler and used in programs that don't need to interact with the environment outside. The second one is used when your program needs to process inputs directly from the user or another program.
     
  4. Global Visibility: The main() function must be globally visible to other parts of your program. This means it cannot be tucked away inside another function or hidden from parts of your program that might need to call it.
     
  5. No Multiple Definitions: You can only have one main() function in any single C program. Having more than one will confuse the compiler and cause errors.
     
  6. Optional Return Type and Arguments: In some cases, particularly in embedded systems, you might see the main() function written without a return type or any arguments. However, this is less common and generally not recommended for standard applications.

Types of C main() Functions

In C programming, the main() function can appear in a few different forms depending on what the program needs to do. Here, we'll look at some common types of main() functions you actually need to learn and understand : 

Main Function with No Arguments and Void Return Type

The simplest version of the main() function in C programming is the one where it doesn't take any arguments and doesn’t return a value to the operating system. This type is written as void main(). Let’s explore what this means and look at an example to understand how it works.

Syntax

When you see void main(), the void part means that this function isn’t going to return any information when it’s done. Here’s how you might write this type of function:

#include <stdio.h>
void main() {
    printf("Hello from our program!\n");
}


In this example, the program does its job, which is to print a message to the screen, and then it ends. There is no return statement because the function is defined as void, which means it does not need to return anything.

When to Use

This form of main() is generally used in environments where the return value is not required or used, such as in some embedded systems where the program runs directly on the hardware and doesn’t interact with an operating system. However, for standard applications running on most computer systems, it's better to use int main() so that you can communicate back to the operating system about how the program finished.

Using void main() can be seen in very specific or controlled situations. It’s important to know that while it simplifies the function by removing the need for a return statement, it limits the program’s ability to signal its exit status. Most programming standards and guidelines suggest using int main() with a return value for greater flexibility and clarity in communication with the operating system.

Main Function with No Arguments and Int Return Type

The most common type of main() function in C programming is one that does not accept any arguments but returns an integer to the operating system. This setup is used to communicate the status of program execution—whether it ran successfully or if there were errors. Let's see in detail how this works.

Syntax

This version of the main() function is declared as int main(). Here's an example:

  • C

C

#include <stdio.h>

int main() {

   printf("Welcome to our simple program!\n");

   // Perform some actions here

   return 0;  // 0 means everything went well

}

Output

Welcome to our simple program!

In this code, int main() tells us that the function will return an integer. The return 0; statement at the end of the function is very important. It sends a signal back to the operating system. Here, 0 usually means that the program finished without any problems. If there were issues, you might return a different number to tell the operating system what kind of error happened.

When to Use

This form of the main() function is suitable for almost all applications that run on a general-purpose operating system like Windows, macOS, or Linux. It helps you manage errors by returning different codes when different problems occur, making it easier to troubleshoot and maintain the software.

For instance, you might decide to return 1 if the program fails due to an input error, or 2 if there’s a problem with reading a file. This way, whoever uses or tests your program can see not just that it failed, but why it failed.

Using int main() with a return type is a good practice for professional programming because it aligns with standards and expectations in the software development community. It provides a clear and structured way to communicate the outcome of your program, which is crucial for debugging and for users to understand the program’s behavior.

Main Function with Command Line Arguments

For more advanced C programs that need to interact with users right when they start, the main() function can be set up to take command line arguments. This allows users to give inputs that affect how the program runs. Let's see what this looks like and how it functions.

Syntax

The syntax for this version of the main() function includes parameters to capture the arguments passed from the command line: int main(int argc, char *argv[]). 
 

  • int argc: This stands for "argument count." It counts how many arguments you pass to your program, including the name of the program itself.
     
  • char *argv[]: This is an array of character strings (or an array of pointers to characters) that hold the actual arguments passed to your program. argv[0] is the name of the program.

Here's a simple example to show you how it works:

  • C

C

#include <stdio.h>

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

   printf("This program was called with %d command-line arguments.\n", argc - 1);

   for (int i = 1; i < argc; i++) {

       printf("Argument %d: %s\n", i, argv[i]);

   }

   return 0;

}

Output

This program was called with 0 command-line arguments.


In this example, the program prints out how many arguments were passed to it (excluding the program's own name), and then it lists each argument. If you ran this program from a command line like this:

./myprogram Hello World

The output would be:

This program was called with 2 command-line arguments.
Argument 1: Hello
Argument 2: World

When to Use

This form of the main() function is very useful for programs that might need to process different kinds of inputs that change each time you run them. For example, if you’re writing a program that processes files, you could use command line arguments to specify which files to process.

Using command line arguments can make your programs much more flexible and powerful because they can be adjusted easily without changing the code. They are especially useful in scripting, automation tasks, or when creating software tools that need to be versatile and adapt to different user needs.

Frequently Asked Questions

What happens if I don’t use any return statement in int main()?

If you don't include a return statement in int main(), the behavior is compiler-dependent. Some compilers might automatically return 0, indicating successful execution, while others might return a random value, leading to unpredictable results.

Can I have more than one main() function in a C program?

No, a C program can only have one main() function. Having more than one main() function leads to a compilation error as the compiler won't know where to start the program.

Is it necessary to use command line arguments in main()?

No, it's not necessary to use command line arguments unless your program specifically needs to process input given at the time of execution. For simple programs, you can use int main() without parameters.

Conclusion

In this article, we have learned about the various forms of the main() function in C programming, which serves as the entry point for all executions. We discussed its basic syntax, the significance of its return type, and how it can handle command-line arguments to enhance flexibility. Each type of main() function has its specific uses, whether for simple applications or more complex ones requiring user input. Understanding these differences is crucial for writing effective C programs that are adaptable to a range of tasks and user needs. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Topics covered
1.
Introduction
2.
Syntax of C main() Function
2.1.
C
2.2.
C
3.
Important Points about C main() Function
4.
Types of C main() Functions
4.1.
Main Function with No Arguments and Void Return Type
4.1.1.
Syntax
4.1.2.
When to Use
4.2.
Main Function with No Arguments and Int Return Type
4.2.1.
Syntax
4.3.
C
4.3.1.
When to Use
4.4.
Main Function with Command Line Arguments
4.4.1.
Syntax
4.5.
C
4.5.1.
When to Use
5.
Frequently Asked Questions
5.1.
What happens if I don’t use any return statement in int main()?
5.2.
Can I have more than one main() function in a C program?
5.3.
Is it necessary to use command line arguments in main()?
6.
Conclusion