Why can't I define a function inside another function?

后端 未结 11 1891
陌清茗
陌清茗 2020-11-27 16:55

This is not a lambda function question, I know that I can assign a lambda to a variable.

What\'s the point of allowing us to declare, but not define a function insid

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 17:31

    Actually, there is one use case which is conceivably useful. If you want to make sure that a certain function is called (and your code compiles), no matter what the surrounding code declares, you can open your own block and declare the function prototype in it. (The inspiration is originally from Johannes Schaub, https://stackoverflow.com/a/929902/3150802, via TeKa, https://stackoverflow.com/a/8821992/3150802).

    This may be particularily useful if you have to include headers which you don't control, or if you have a multi-line macro which may be used in unknown code.

    The key is that a local declaration supersedes previous declarations in the innermost enclosing block. While that can introduce subtle bugs (and, I think, is forbidden in C#), it can be used consciously. Consider:

    // somebody's header
    void f();
    
    // your code
    {   int i;
        int f(); // your different f()!
        i = f();
        // ...
    }
    

    Linking may be interesting because chances are the headers belong to a library, but I guess you can adjust the linker arguments so that f() is resolved to your function by the time that library is considered. Or you tell it to ignore duplicate symbols. Or you don't link against the library.

提交回复
热议问题