为什么argc不是常数? [英] Why is argc not a constant?

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

问题描述

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

由于 Effective C ++ 项目#3说明尽可能使用const,我开始思考为什么不会使这些常量参数 const ?。

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

推荐答案

在这种情况下,历史记录是一个因子。 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.

(Aside:有趣的是,虽然 getopt 的原型表明它不会修改 argv [] 但可以修改指向的字符串,Linux手册页指示 getopt 排列其参数,并且显示他们知道他们是顽皮的。开放组的人页不提)

(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 放在 argc argv 不会购买太多,并且会使一些老式编程习惯无效,例如:

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写了这样的程序,我知道我不是孤独的。我从某处复制了示例

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆