PDA

View Full Version : prototyping functions in C++


inkedmn
04-18-2003, 08:21 PM
i'm reading through this C++ tutorial and it's got this code:

#include <iostream.h>

int mult(int x, int y);

int main() {
int x, y;

cout<<"Please input two numbers to be multiplied: ";
cin>>x>>y;
cout<<"The product of your two numbers is "<<mult(x, y);
return 0;
}

int mult(int x, int y) {
return x*y;
}


now, i understand the second line is a function prototype, but it doesn't really say why that's done or if it's required for every function written (except main()).

eh?

EscapeCharacter
04-19-2003, 01:39 AM
in that example its not really needed but if you didnt have the prototype you would have to move the declaration of mult from below main to above it. prototypes are mostly used in .h files. say you had main.cpp and blah.h and blah.cpp. if you declared mult in blah.h but had the def in blah.cpp, main wouldnt know what to do when it was called from main. so you would have included blah.h in main.cpp just to get the prototype and then link blah.o and main.o together where main would finally know what mult did. ofcourse thats over complicating something this small but i believe thats how most people write bigger projects(if not ive been doing something wrong for a while :))

inkedmn
04-19-2003, 02:51 AM
sweet, that makes perfect sense :)

thanks duder