gpt4 book ai didi

c++ - "extern"在函数内部?

转载 作者:IT老高 更新时间:2023-10-28 21:51:51 25 4
gpt4 key购买 nike

好吧,阅读“有点老”的书(“The C programming language”,第二版,Dennis Ritchie 着),我遇到了以下问题:

An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it

我当时想 - 什么?!

“该变量也必须在每个想要访问它的函数中声明”。然后,我又震惊了一次:

int max; 
/* ... */
int main()
{
extern int max;
/* ... */
}

还有一个 - 什么?!


据我所知(显然,这还远远不够),extern 仅在您在某处定义全局变量并且您想通过另一个文件访问它时才有意义(而不是再次定义)。

所以:

  • extern int max inside main 或任何其他函数有什么意义?
  • 标准是否真的说这是一个必须(我需要在每个例子中声明这个max函数,那会用吗?)
  • 这对于 C++ 是否相同(这就是我放置 C++ 标签的原因)?这是我第一次看到这样的东西。

注意:这与 What is the use of declaring a static variable as extern inside a function? 不同。

最佳答案

你的帖子让我吃惊。我不记得了,我很久以前就读过 K&R。我这里只有第一版,它也在那里。然而,这并不是它所说的全部。从第一版开始:

The variable must also be declared in each function that wants to access it; this may be done either by an explicit extern declaration or implicitly by context.

注意“根据上下文隐式”。正文后面:

...if the external definition of a variable occurs in the source file before its use in a particular function, then there is no need for an extern declaration in the function. The extern declarations in main, ... are thus redundant. In fact, common practice is to place definitions of all external variables at the beginning of the source file, and then omit all extern declarations.

也就是说,使 extern 变量可见可以在函数内部完成,也可以在任何函数外部完成,在源文件中跟随它的所有函数。我相信这是本书中唯一在函数内部完成的地方,后来它使用熟悉的一次文件方法。

关于c++ - "extern"在函数内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com