Is it possible to give arguments in the main() function in C language?


Yes, we can give arguments in the main() function.

Command line arguments in C are specified after the name of the program in the system’s command line, and these argument values are passed on to your program during program execution.

The argc and argv are the two arguments that can pass to main function.

But main() function is actually called by the operating system (or shell program) when you run the program from the terminal.

Syntax

The syntax is explained below −

int main(int argc, char *argv[]){
   //Code
   return 0;
}

Example

 Live Demo

#include<stdio.h>
int main(int argc, char *argv[]){
   int i;
   for (i = 0; i < argc; i++) {
      printf("Arg %d: %s
", i, argv[i]);    }    return 1; }

Output

Arg 0: G:\CP\CP programs\main with arguments.exe
Explanation:
The program that prints all the arguments passed to your program, including the program name itself.

Updated on: 09-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements