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.

Chapter 6: Creating Functions 87This is the same FunctionDemo() program, except that SquareDemo()accumulates the square of the values entered. The function square()returns the value of its one argument multiplied by itself. The change tothe sumSequence() function is simple — rather than accumulate the valueentered, the function now accumulates the result returned from square().Functions with multiple argumentsFunctions may have multiple arguments that are separated by commas. Thus,the following function returns the product of its two arguments:int product(int arg1, int arg2){return arg1 * arg2;}main() exposedThe “keyword” main() from our standard program template is nothing morethan a function — albeit a function with strange arguments — but a functionnonetheless.When a program is built, C++ adds some boilerplate code that executes beforeyour program ever starts (you can’t see this code without digging into thebowels of the C++ library functions). This code sets up the environment inwhich your program operates. For example, this boilerplate code opens thedefault input and output channels cin and cout.After the environment has been established, the C++ boilerplate code callsthe function main(), thereby beginning execution of your code. When yourprogram finishes, it exits from main(). This enables the C++ boilerplate toclean up a few things before turning control over to the operating system thatkills the program.Overloading Function NamesC++ allows the programmer to assign the same name to two or more functions.This multiple use of names is known as overloading functions.In general, two functions in a single program cannot share the same name. Ifthey did, C++ would have no way to distinguish them. Note, however, that thename of the function includes the number and type of its arguments — butdoes not include its return argument. Thus the following are not the samefunctions:

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

Saved successfully!

Ooh no, something went wrong!