2

Passing argc to main seems to be redundant. Take a look at the following example.

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

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

  for (j = 0; j < argc; j++)
    printf("argv[%d]: %s\n", j, argv[j]);

  for (j = 0; envp[j] != NULL; j++)
    printf("envp[%d]: %s\n", j, envp[j]);

  for (j = 0; argv[j] != NULL; j++)
    printf("argv[%d]: %s\n", j, argv[j]);

  exit (EXIT_SUCCESS);
}

The first for loop uses the standard way using argc to enumerate the command line arguments.

The second loop shows how to enumerate the environment. The environment is stored in a list of pointers terminated by a NULL. The number of entries in the environment is not passed to main.

And the same applies to the list of arguments. The third loop shows how to enumerate the arguments without the use of argc.

So the question is: why is argc it passed to main if it is redundant?

ceving
  • 21,900
  • 13
  • 104
  • 178
  • 6
    Because someone found that convenient around 1973? – Bo Persson Aug 24 '15 at 09:17
  • 6
    Because you might not want to be looping through `argv` to determine its length if you _know_ that you need at least 4 arguments. `if (argc != 5)` is a lot shorter to write, don't you think? – Elias Van Ootegem Aug 24 '15 at 09:21
  • although your question is duplicate it seems a little bit special because you're speaking about redundancy . but I assure to you that if it was redundant it would not be in a language such C language. – L.Zak Aug 24 '15 at 09:34
  • 2
    @ring0: Not sure what you're saying, but the standard explicitly states that `argv[argc]` _"shall be NULL"_ and that _"the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings"_. (cf 5.1.2.2.1 Program startup). It goes on to say that an empty value ie unknown program name shall be `argv[0][0] == '\0';`, so not a `NULL` pointer, by any means – Elias Van Ootegem Aug 24 '15 at 10:07

0 Answers0