Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to rename argc and argv in main function?

Tags:

c++

c

main

A lot of programs use standard names for a number of arguments and arrays of strings. The prototype of main function looks like: int main(int argc, char *argv[]);. But would I break something if I choose custom names for these variables?

E.g. int main(int n_of_args, char *args[]);

In the context of the compiler, everything is fine. These variables are local for main function, so they may have any names. And the simple code builds and runs perfectly. But these names may be used by preprocessor. So is it safe to rename these arguments?

PS Personally I find these names bad, because they look very similar and differ in only one letter. But EVERYONE uses them for some kind of reason.

like image 504
yanpas Avatar asked Apr 29 '16 18:04

yanpas


People also ask

Is it safe to modify argv?

Once argv has been passed into the main method, you can treat it like any other C array - change it in place as you like, just be aware of what you're doing with it.

Can we use any name in place of argv and argc as command line arguments in C?

You can name the parameters whatever you want, but they're almost always called argc and argv .

What is argc and argv in main function?

The first parameter, argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. The second parameter, argv (argument vector), is an array of pointers to arrays of character objects.

Can we have different command line arguments names other name argc and argv?

Standard command-line arguments The types for argc and argv are defined by the language. The names argc and argv are traditional, but you can name them whatever you like.


1 Answers

Yes, it is safe, so long as you use valid variable names. They're local variables, so their scope doesn't go beyond the main function.

From section 5.1.2.2.1 of the C standard:

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /*  ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

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

or equivalent; or in some other implementation-defined manner

That being said, using anything other than argc and argv might confuse others reading your code who are used to the conventional names for these parameters. So better to err on the side of clairity.

like image 93
dbush Avatar answered Oct 02 '22 12:10

dbush