C function declaration within another function

2019-02-13 15:55发布

can anyone explain these lines to me:

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

a function declaration within a function definition? or am I missunderstanding something?

5条回答
Anthone
2楼-- · 2019-02-13 16:21

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.

查看更多
Lonely孤独者°
3楼-- · 2019-02-13 16:22

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

查看更多
ら.Afraid
4楼-- · 2019-02-13 16:26

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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-02-13 16:32

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

查看更多
一夜七次
6楼-- · 2019-02-13 16:38

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.

查看更多
登录 后发表回答