“extern” inside a function?

后端 未结 3 1215
半阙折子戏
半阙折子戏 2020-12-31 00:51

Well, reading \"a bit old\" book (\"The C programming language\", second edition, by Dennis Ritchie), I came a cross the following:

An external variab

相关标签:
3条回答
  • 2020-12-31 00:54

    Your post surprised me. I had no recollection of that and I've read K&R long ago. I only have the first edition here and it is there too. However, that is not all it says. From the first edition:

    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.

    Note the "implicitly by context." Later in the text:

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

    So this is saying that making the extern variable visible can be done inside the function for just that function, or can be done outside any function for all functions following it in the source file. I believe that this is the only place in the book where it is done inside the function, later it uses the familiar once for the file approach.

    0 讨论(0)
  • 2020-12-31 00:59

    The extern is linkage. It means this name, max, is linked to other occurrences of the name, possibly in other files. (That is, when the object modules are linked together to make an executable, all the linked references to this name will be made to refer to the same object.)

    The scope of this declaration is the remainder of the function body it is in. That means other functions in this file do not see the name declared by this declaration (unless they declare it themselves).

    Scope and linkage are different things.

    0 讨论(0)
  • 2020-12-31 01:06

    extern int max inside main or function is saying to the compiler "I am not a local variable inside the main or function, I am the global variable defined elsewhere".

    If the global is declared in the same file, not useful. In different file,yes, but not in each function, just declare one time in the head file of the source that use this global variable. This is the same in c++.

    0 讨论(0)
提交回复
热议问题