Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 101

5


When you call a function, it can do work and then send back a value as a result of that
work. This is called its return value, and the type of that return value must be declared.
Thus, if you write
int myFunction();
you are declaring a function called myFunctionthat will return an integer value. Now
consider the following declaration:
int myFunction(int someValue, float someFloat);
This declaration indicates that myFunctionwill still return an integer, but it will also take
two values.
When you send values intoa function, these values act as variables that you can manipu-
late from within the function. The description of the values you send is called a parame-
ter list. In the previous example, the parameter list contains someValuethat is a variable
of type integer and someFloatthat is a variable of type float.
As you can see, a parameter describes the type of the value that will be passed into the
function when the function is called. The actual values you pass into the function are
called the arguments. Consider the following:
int theValueReturned = myFunction(5,6.7);
Here, you see that an integer variable theValueReturnedis initialized with the value
returned by myFunction, and that the values 5 and 6.7are passed in as arguments. The
type of the arguments must match the declared parameter types. In this case, the 5 goes
to an integer and the 6.7goes to a floatvariable, so the values match.

Declaring and Defining Functions ......................................................................


Using functions in your program requires that you first declare the function and that you
then define the function. The declaration tells the compiler the name, return type, and
parameters of the function. The definition tells the compiler how the function works.
No function can be called from any other function if it hasn’t first been declared. A dec-
laration of a function is called a prototype.
Three ways exist to declare a function:


  • Write your prototype into a file, and then use the #includedirective to include it
    in your program.

  • Write the prototype into the file in which your function is used.

  • Define the function before it is called by any other function. When you do this, the
    definition acts as its own prototype.

Free download pdf