fast question about functions

is it best just to include the function prototype and definition at the top of the code instead of declaring a prototype and then defining the function at the end of int main()? or is it just a personal choice? or depending on in-house rules?
I'd say it depends on in-house rules / personal preference.

I prefer to include a prototype, especially if it's in a single file with main. I don't want to have to scroll down a couple of hundred lines before I get to the entry point of the program.

Coincidentally, this is the convention in my workplace.
It's best to to include,only the function prototype at the top of the code

because when your compiler starts to compile the program It examines every line above the main() function ,so It takes much time than declaring just prototype ,

I hope I am wrong
Let consider at first the simple example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int f( int x, int y );
char *g( const char *s );
void h( const char *,... );

int main()
{
  int x = 10, int y = 20;

   int z = f( x, y );

   char *p = g( "Error message" );

   h( p, x, y, z );
}


int f( int x, int y )
{
/* some code */
}

char *g( const char *s )
{
/* some code */
}

void h( const char *,... )
{
/*some code */
}
 


Such a program is difficult to read, because I should consider the code in the main knowing nothing about what these functions do. So at first I have to skip the code in main look the function definitions in the very end of the program and then return to code of the main anew.

So if your porgram is ismilar as this program relative its size and the number of modules it is better to place functions definitions before main.

If your project contains several modules then usually function definitions are placed in separate modules. In this case all prototypes of functions with external linkage are placed in headers while their definitions are placed in modules. Insde a module with such function definitions it is bettter to place definitions of functions with internal linkage before definitions of functions with external linkage.
Last edited on
Thx everyone!
In the in-house rules I live by, main() is always the only function in its file.
Topic archived. No new replies allowed.