C Command line arguments

Command line arguments are a way to pass information to a C program from the command line when it is run. Command line arguments are stored in the argv[] array, which is a pointer to an array of strings that represent the arguments passed to the program.

The argc variable stores the number of command line arguments passed to the program. The first command line argument, argv[0], is always the name of the program itself.

The following is an example program that takes two integer values as command line arguments and adds them together:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
   int num1, num2, sum;
   
   if (argc != 3) {
      printf("Error: expected two command line arguments\n");
      return 1;
   }
   
   num1 = atoi(argv[1]);
   num2 = atoi(argv[2]);
   
   sum = num1 + num2;
   
   printf("%d + %d = %d\n", num1, num2, sum);
   
   return 0;
}

In this program, the atoi() function is used to convert the command line arguments from strings to integers. If the user does not provide exactly two command line arguments, an error message is printed and the program returns a non-zero exit code.

Command line arguments are a powerful tool for passing information to a C program from the command line, and can be used for a wide range of purposes, from simple data input to more complex program configuration.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial