Search code examples
ccommand-line-arguments

C main function const char*[] vs char*[]


I don't understand what the difference between

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

and

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

is.

I'm aware of the difference between a char*[] and const char*[] but I wonder why one would like to use the latter.

Are there use cases where one would want to change command line arguments? What's the best practice about adding const?


Solution

  • int main(int argc, char *argv[]) is a defined way of declaring main for a hosted environment according to the C standard, per C 2018 5.1.2.2.1 1. int main(int argc, const char *argv[]) is not.

    It is good to use const where applicable to indicate that the pointed-to objects will not change, but it must be used appropriately. The types char *[] and const char *[] are not compatible and are not interchangeable as parameter declarations or argument types. If main is declared with const char *argv[], the behavior is not defined by the C standard.

    As for why the prescribed declaration is char *argv[] rather than const char *argv[], that is partly historical and partly because some techniques for processing command-line arguments modify the arguments in place.