Why is argc not a constant?(为什么 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
放在 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 编写过这样的程序,而且我知道我并不孤单.我从 somewhere 复制了示例.
I've written such programs in C, and I know I'm not alone. I copied the example from somewhere.
这篇关于为什么 argc 不是常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 argc 不是常数?
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- C++ 数据结构超详细讲解顺序表 2023-03-25
- Easyx实现扫雷游戏 2023-02-06
- C语言详解float类型在内存中的存储方式 2023-03-27
- Qt计时器使用方法详解 2023-05-30
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- ubuntu下C/C++获取剩余内存 2023-09-18
- C语言qsort()函数的使用方法详解 2023-04-26
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30