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

CServer Side ProgrammingProgramming

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\n", 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.
raja
Published on 08-Mar-2021 12:55:56
Advertisements