Perhaps a different perspective might be helpful.
1 2 3 4 5 6 7
|
int DoSomething( int i )
{
int j = 0;
j = i * 3;
return j;
}
|
This is a pretty generic function. We refer to this as the implementation of the function since this is the part which actually contains all the internal logic of the function. Why we need the distinction of the term 'implementation' I'll explain later.
now I'll show a generic program with uses our function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int main()
{
int a = 2;
int b = 3;
int c = 0;
int d = 0;
c = DoSomething( a );
d = DoSomething( b );
}
int DoSomething( int i )
{
int j = 0;
j = i * 3;
return j;
}
|
Looks fairly simple right, any idiot could follow that program. Except your compiler is a lot dumber than you give it credit for. The compiler starts at the top of the file and works it's way down, and the instant it encounters something it doesn't know how to handle, it generates errors and stops. The problem here, is that when it runs into the line
c = DoSomething( a );
in main, the compiler doesn't know what to do. It has no idea what 'DoSomething()' is, because it's never seen it before and doesn't know how to handle the function call.
This is why we have 'declarations' of functions in addition to the 'implementation' of functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
int DoSomething( int i );
int main()
{
int a = 2;
int b = 3;
int c = 0;
int d = 0;
c = DoSomething( a );
d = DoSomething( b );
}
int DoSomething( int i )
{
int j = 0;
j = i * 3;
return j;
}
|
Here's the final bit... the first line is the function declaration (also called a prototype). this just tells the compiler what the function looks like (what type of parameters are passed, and what type the return value is). That's all the information the compiler really needs to generate a working
call to the function when it hits the
c = DoSomething( a );
line, so now that it knows what to do, it can successfully compile the whole program.
Does this clarify the distinction between declaration and implementation?