Is main() function better on top of all other functions? [closed]

My college professor told me that main functions should be defined on top of other function definitions. We should use a forward declaration in order to accomplish this (we use C at that time). So yes, my question is why should main() be on top of other function definitions? Does this apply to all programming languages that uses main() as the entry point of the program?

3

It’s largely a matter of personal preference, although some places may make it a formal coding standard. C itself doesn’t care.

For my part, if I’m defining multiple functions in a single source file, I will define the called functions before the caller:

void foo( void )
{
  ...
}

void bar( void )
{
  ...
  foo();
  ...
}

int main( void )
{
  ...
  bar();
  ...
}

instead of

int main( void )
{
   void bar( void );
   ...  
   bar();
   ...
}

void bar( void )
{
  void foo( void );
  ...
  foo();
}

void foo( void )
{
  ...
}

The problem with using forward declarations is you increase your maintenance burden; if you change the function prototype (return type, number and/or types of parameters), you now have to make those changes in two places instead of one.

Of course, if you’re calling functions defined in a different source file, you need separate declarations (preferably grouped into their own header file):

/**
 * functions.c
 */
#include "functions.h"

void foo( void )     // Note that I'm still defining called functions
{                    // before their callers, even though in this case
  ...                // it's not necessary, since "functions.h" contains
}                    // the declaration for foo().

void bar( void )
{
  ...
  foo();
  ...
}

/**
 * functions.h
 */
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void foo( void );
void bar( void );

#endif

/**
 * main.c
 */
#include "functions.h"

int main( void )
{
  ...
  bar();
  ...
}

Does this apply to all programming languages that uses main() as the entry point of the program?

Again, for most of those languages, it’s strictly a matter of style and personal preference. The language definition itself doesn’t care.

The best place is somewhere that people can find it.

In the middle of a very large file is bad. At the top is good, but others might prefer right at the bottom.

Forward declaring main() doesn’t help, and is often pointless anyway – because it’s very unusual to explicitly call main() from within your code.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *