11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

90 Part II: Becoming a Functional C++ ProgrammerThe target functions sumSequence() and square() — appearing earlier inthis chapter — are both defined in the code that appears before the actualcall. This doesn’t have to be the case: A function may be defined anywherein the module. (A module is another name for a C++ source file.)However, something has to tell the calling function the full name of the functionto be called. Consider the following code snippet:int main(int nNumberofArgs, char* pszArgs[]){someFunc(1, 2);}int someFunc(double arg1, int arg2){// ...do something}main() doesn’t know the full name of the function someFunc() at the time ofthe call. It may surmise from the arguments that the name is someFunc(int,int) and that its return type is void — but as you can see, this is incorrect.I know, I know — C++ could be less lazy and look ahead to determine the fullname of someFunc()s on its own, but it doesn’t. It’s like my crummy car; itgets me there, and I’ve learned to live with it.What is needed is some way to inform main() of the full name of someFunc()before it is used. This is handled by what we call a function prototype.A prototype declaration appears the same as a function with no body. In use,a prototype declaration looks like this:int someFunc(double, int);int main(int nNumberofArgs, char* pszArgs[]){someFunc(1, 2);}int someFunc(double arg1, int arg2){// ...do something}The prototype declaration tells the world (at least that part of theworld after the declaration) that the extended name for someFunc() issomeFunction(double, int). The call in main() now knows to castthe 1 to a double before making the call. In addition, main() knows thatthe value returned by someFunc() is an int.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!