Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

int main( const int argc , const char[] const argv)

As Effective C++ Item#3 states "Use const whenever possible", I start thinking "why not make these 'constant' parameters const"?.

Is there any scenario in which the value of argc is modified in a program?

See Question&Answers more detail:os

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

1 Answer

In this case, history is a factor. C defined these inputs as "not constant", and compatibility with (a good portion of) existing C code was an early goal of C++.

Some UNIX APIs, such as getopt, actually do manipulate argv[], so it can't be made const for that reason also.

(Aside: Interestingly, although getopt's prototype suggests it won't modify argv[] but may modify the strings pointed to, the Linux man page indicates that getopt permutes its arguments, and it appears they know they're being naughty. The man page at the Open Group does not mention this permutation.)

Putting const on argc and argv wouldn't buy much, and it would invalidate some old-school programming practices, such as:

// print out all the arguments:
while (--argc)
    std::cout << *++argv << std::endl;

I've written such programs in C, and I know I'm not alone. I copied the example from somewhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...