Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...