Home > Net >  Is it valid to use const char*[] as the type of second parameter of main
Is it valid to use const char*[] as the type of second parameter of main

Time:04-22

I am learning C and learnt that the following given declarations are equivalent:

int main (int argc, char *argv[]); //first declaration
int main (int argc, char **argv);  //RE-DECLARATION. Equivalent to the above declaration

My question is that if i change the declaration to say:

//note the added const
int main (int argc,const char *argv[]); //IS THIS VALID? 

Is the above declaration where i have added a const valid? That is, does the C standard allow this modified declaration with the added const.

CodePudding user response:

Adding const changes the type of the function. It is not declaration of the same function.

Whether that is valid for main in particular, depends on language implementation:

[basic.start.main]

An implementation shall not predefine the main function. Its type shall have C language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined. An implementation shall allow both

  • a function of () returning int and
  • a function of (int, pointer to pointer to char) returning int

as the type of main ([dcl.fct]).

It may in theory be valid in some implementation, but it will not be portable to all systems.

CodePudding user response:

According to cppreference.com (main_function), main should have one of the following forms:

int main () { body }    (1)     
int main (int argc, char *argv[]) { body }  (2)     
/* another implementation-defined form, with int as return type */  (3)

Using int main (int argc,const char *argv[]) (your suggested variation) works for example in MSVC. This case falls under form (3) above.

But since it is implementation-defined it is better to avoid (even if works in your current environment).

  • Related