Function prototype declared inside main - best practice?

前端 未结 5 1014
心在旅途
心在旅途 2020-12-03 18:09

Is this a good style to have the function prototype declared inside of the main function?

I was looking at a C tutorial, I think is quite out of date. However, they

相关标签:
5条回答
  • 2020-12-03 18:37

    I personally would say "no" for several reasons:

    • it makes the code for main longer
    • it may confuse a newbie into think ing the function is scoped by main
    • in real code, I would normally put the function in a different compilation unit and #include its header file
    0 讨论(0)
  • 2020-12-03 18:37

    I'll also say no with the additional reason that if you start using explicit declarations all over the code, you will most definitely get unresolved externals when the function you are calling suddenly changes its signature. If you have ONE declaration in ONE header file, you only need to change ONE declaration when the function changes.

    However, I'd say yes because of the following reason: If you are just writing a simple test method that's written for a single use only, i.e. if you want to test something really quick and then discard the function right away. Then it can be nifty to just throw in a declaration right before you want to make the call.

    For production code -> No no no ! :)

    0 讨论(0)
  • 2020-12-03 18:37

    i think that's just a small example for the tutorial... this is what you do when you start to introduce functions...

    I agree with Neil...

    0 讨论(0)
  • 2020-12-03 18:55

    It's not a good style.

    Either declare the local function prototypes at the beginning or move them to a header-file.

    Function protoypes (and external variables as well) can be declared almost everywhere in the c-language. However, just because it's possible shouldn't be no reason to write spaghetti style C.

    It makes the code less readable. For me such practices are a clear sign of code-smell.

    0 讨论(0)
  • 2020-12-03 18:59

    Since I haven't jumped through the required number of hoops in this pony show I have no choice but to post this comment as an answer.

    Keep in mind that this is just a snippet from a book and not the kind of code that one sees in a production environment. The code snippet is fine but not ideal. Neil gave the best answer so I gave him +1. I would note his 3rd point if you really want to know how it's done outside of tutorial/text books.

    Also, a point since I'm making them: the "stdio.h" vs is simply a way of telling the preprocessor where to search for the file stdio.h. Again, in most situations you will see stdio.h surrounded by <> instead of "". However, your own header files, as mentioned by Neil's 3rd point, will be surrounded by "".

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