Sams Teach Yourself C++ in 21 Days

(singke) #1
In main
In Demonstration Function
Back in main
The functionDemonstrationFunction()is defined on lines 6–8. When it is
called, it prints a message to the console screen and then returns.
Line 13 is the beginning of the actual program. On line 15,main()prints out a message
saying it is in main(). After printing the message, line 16 calls
DemonstrationFunction(). This call causes the flow of the program to go to
the DemonstrationFunction()function on line 5. Any commands in
DemonstrationFunction()are then executed. In this case, the entire function consists of
the code on line 7, which prints another message. When DemonstrationFunction()
completes (line 8), the program flow returns to from where it was called. In this case, the
program returns to line 17, where main()prints its final line.

Using Functions................................................................................................


Functions either return a value or they return void, meaning they do not return anything.
A function that adds two integers might return the sum, and thus would be defined to
return an integer value. A function that just prints a message has nothing to return and
would be declared to return void.
Functions consist of a header and a body. The header consists, in turn, of the return type,
the function name, and the parameters to that function. The parameters to a function
enable values to be passed into the function. Thus, if the function were to add two num-
bers, the numbers would be the parameters to the function. Here’s an example of a typi-
cal function header that declares a function named Sumthat receives two integer values
(firstand second) and also returns an integer value:
int Sum( int first, int second)
A parameter is a declaration of what type of value will be passed in; the actual value
passed in when the function is called is referred to as an argument. Many programmers
use the terms parameters and arguments as synonyms. Others are careful about the tech-
nical distinction. The distinction between these two terms is not critical to your program-
ming C++, so you shouldn’t worry if the words get interchanged.
The body of a function consists of an opening brace, zero or more statements, and a clos-
ing brace. The statements constitute the workings of the function.
A function might return a value using a returnstatement. The value returned must be of
the type declared in the function header. In addition, this statement causes the function to
exit. If you don’t put a returnstatement into your function, it automatically returns void

OUTPUT


36 Day 2


ANALYSIS
Free download pdf