C function declaration within another function

后端 未结 5 1142
孤城傲影
孤城傲影 2021-01-05 10:49

can anyone explain these lines to me:

int xyz( void )  
{ 
extern void abc( void );
}

a function declaration within a function definition?

相关标签:
5条回答
  • 2021-01-05 11:29

    Yes your statement is correct.....when we use extern func_name w are are declaring the func_name.

    0 讨论(0)
  • 2021-01-05 11:35

    I would just add that this construct, in my experience, is uncommon in modern code, but often seen in older code, especially "K&R" C code.

    More modern code would usually get the function prototype from a header file.

    0 讨论(0)
  • 2021-01-05 11:41

    The "extern" declaration in C is to indicate the existence of, and the type of, a global variable or function.

    An extern is something that is defined externally to the current module.

    It is also not uncommon to find function prototypes declared as extern.

    You need it only where it's not the default, and/or where you want to specify "C" linkage.

    0 讨论(0)
  • 2021-01-05 11:48

    Yes, your guess is correct. It's declaring the existence of the function abc(), so it may be referenced within xyz(). Note that the extern is unnecessary, as functions are extern by default.

    0 讨论(0)
  • 2021-01-05 11:48

    This way of declaration has one big advantage:

    If only one or less functions are calling an external function, this declaration makes sense especially within a big source file. If a later code restructuring (function move in another file) has to be done, it is much easier to see the dependencies than to add externals on global (file) scope. In the latter case the probability of "forgetting" such externals in a file is higher. In contrast by declaring it in function scope, the declaration will move together with the function...

    I also tend to do so for external global variables - the benefit comes later when maintaining and eventually restructuring / minimizing dependencies.

    One last note to the topic "writing external / not external": If its just a forward declaration (-> the function is defined at end of the the same file), I would not recommend using external - because it simply isn't the case. Otherwise external makes absolute sense to indicate that definition has to be found somewhere else (or for libaries: might need to be implemented by users of that libary).

    Hope this helps (as a step to a more objective oriented programming style.. :) )

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