开发者

function prototypes in main or before main in C

Should the function prototype in C be in main or before main. I was taught before main, but my friends class book shows it in main. Which is the correct way?

His book shows it:

int main()
{
    void numberTable();

    numberTable();
}

void numberTable()
{
    int num;
    ...rest of the code...
}
开发者_StackOverflow社区


Both are correct.
If you add the function declaration inside main, its scope is inside the main { }.
If you add it outside main, its scope is the entire source file.


It can be both way. But If you declare outside main, then you can access everywhere in the code, in other case,its scope is within main.


The reason to define the function before main is to avoid the function declaration that would be necessary if you define the function after main. It is common for C modules to be coded in this style, that is: functions defined in dependency order, in order to avoid the need for declarations of functions that are local in scope (we should be careful how we use the word scope here - scope is not enforced by the C linker).


Both are correct; however, it's not a good style in reality.
A common good practice: put all those functions declaration and definition in other headers and source files: header.h + header.c


Either way can be made to work. Declarations outside main() (or, more generally, outside any function) typically leads to less repetition.

When you declare the function inside main(), that declaration only applies in main(). If some other function (e.g. function_1()) also calls the relevant function (e.g. numberTable()) and appears before the other function is defined, then you have to declare numberTable() inside function_1() as well (violating DRY: Don't Repeat Yourself, and also SPOT: Single Point of Truth). If, on the other hand, the declaration of numberTable() was outside any function and before any function in the file, then all functions can use the one declaration.

If you have multiple source files involved, then the rules become simpler. All functions callable from other files should be declared in a header (header.h). That header should be included in every file that references any of the functions declared in header, and also in each of the files that defines each of the functions that is declared in the header. The header should be included outside of any function in the files where it is used. (The C standard requires this for the standard headers.) This ensures that all the code has a consistent view of declaration of each function. Eventually, you will get to big enough programs that there may even be multiple headers. The same basic rules apply - declare functions in headers; include the headers (outside of any function) where the functions are used and defined. (See also What are extern variables in C.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜