为什么 argc 不是常数?

Why is argc not a constant?(为什么 argc 不是常数?)

本文介绍了为什么 argc 不是常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Effective C++ Item#3 声明尽可能使用 const",我开始思考为什么不让这些‘常量’参数const"?.

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

有没有在程序中修改argc的值的场景?

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

推荐答案

在这种情况下,历史是一个因素.C 将这些输入定义为非常量",并且与(大部分)现有 C 代码的兼容性是 C++ 的早期目标.

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++.

某些 UNIX API,例如 getopt,实际上确实操作 argv[],因此不能将其设为 const还.

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

(旁白:有趣的是,虽然 getopt 的原型表明它不会修改 argv[] 但可能会修改指向的字符串,Linux 人page 表明 getopt 置换了它的参数,并且 看来他们知道他们很淘气.Open Group 的手册页没有提到这种排列.)

(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.)

const 放在 argcargv 上不会买太多,而且会使一些老式的编程实践失效,例如:

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;

我已经用 C 编写过这样的程序,而且我知道我并不孤单.我从 somewhere 复制了示例.

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

这篇关于为什么 argc 不是常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 argc 不是常数?