Why create prototypes?

I'm reading this book, and I see they use examples as:

1
2
3
4
5
6
7
8
9
int myFunc( int );

int main(){
  // Do something
}

int myFunc( int n ){
  // Do something
}


Why the need to create the initial prototype? Why don't they just move the whole definition of myFunc to the top of the file?

I'm a total newbie, but I take it this is the beginner forum?:)
closed account (z05DSL3A)
Here is an example where you need to use prototypes:
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
int myFunc1( int );  
int myFunc2( int );

int myFunc1( int n )
{
    // Do something
    if(somecodition)
        return myFunc2( n );
    else
        return n;
}

int myFunc2( int n )
{
    // Do something
    if(somecodition)
        return myFunc1( n );
    else
        return n;
}

int main()
{
      int t = myFunc1( 1 );
}


Technicaly in this case you would only need to prototype int myFunc2( int );.
i would only like to add that the function prototype simply tells the compiler on your behalf that" i am going to use this function in my program. You have all the details (given by the prototype) please make the suitable arrangements "
I think I understand.. It's for being able to call the functions at all times, even though its not been necessarily declared yet?

In that case it makes sense to me. Thanks for your replies!
A prototype is the function declaration, so is better saying
"It's for being able to call the functions at all times, even though its not been necessarily implemented yet"
The C++ standard requires that a symbol be defined before it is used. Function names are symbols.

Why is this useful for functions? So that the compiler can make sure you are calling the function with the right number of parameters and the right type of parameters. Anyone who has done K&R C has probably been bitten more than once by the fact that the compiler didn't complain about a call to foo() with 3 actual parameters, but the function really took 4, and then things didn't quite work right when the program ran.

[NB: Now there's more to this than just what I mentioned above. OO and polymorphism, not to mention templates, would be impossible without prototypes/declarations.]
Topic archived. No new replies allowed.