C++ DOS console, Tutorial 3
By: Dennis Dunn
Original: 9-6-01
Updated: 12-28-10
This tutorial covers:
KEY Colors:
- Normal text
- Comments
- Key words
- Special cases that are being pointed out
- Special syntax that is being pointed out
- Sample output for a program
- Hyper links
– [ ] Represents input for a sample run of a program
Functions are used to perform a specific action. They make programming a lot easier and less confusing.
The main function, is an example of a function. It has the name "main" and a body that is enclosed within braces {}. You can create your own functions that can be "called" and their internal code will be executed. Each function may return a single value after completion.
The purpose of the data types will be explained in section 4, so we will use the "void" data type for now. Section 4 will explain what the data types are used for.
_______________________________________________________________________
Functions, like variables, must be defined first. This is called a function prototype and it looks like this:
void function_name();
Notice the parenthesis () and the semicolon ";" are needed at the end.
_______________________________________________________________________
In order for a function to execute it must then be called. This is named the call function and it looks like this:
function_name();
Notice the semicolon ";" is still needed at the end, but the data type (void, etc.) is no not placed in front. This is exactly how the printf(); function works.
_______________________________________________________________________
The contents of a function are put after the function header. It looks like this:
void function_name()
{
//contents of function goes here
}
Notice the semicolon ";" is NOT at the end and the data type (void, etc.) is put in front of the function name.
_______________________________________________________________________
Function Review:
Prototype: void function_name();
Call: function_name();
Header: void function_name() {function body}
After a function is initialized and called, whatever code is inside of the body {} will be executed and the program will then return to the place it left off before the function was called.
Ex. 1.1
void display(); //function prototype
void main()
{
cout << " Inside of the main function now."<<endl;
display(); //call display function
cout << " Out of display function."<<endl;
}
void display() //function header
{
//This text will be displayed when the function is called
cout << " Inside of display function!"<<endl;
}
This program will output:
Inside of the main function now.
Inside of display function!
Out of display function.
The cool thing about functions is that they can be called as many times as needed. It’s easy if you need to repeat a process in your program.
There are two types of variables, global and local. The difference between the two is that:
Locals - are created/initialized inside of a function each time it is called. All of the variables created in the "main" function are locals. Local variables can only be used in the function that they were created in. Aka. their "scope" is limited to within their containing function. Also note that the variable is deleted after the function completes, and if you call multiple instances of the same function, each instance has its own local variable instance also.
Globals - are created outside of any function and can be used by all of the functions in a program. This isn't recommended as the variable can be changed anywhere and leads to messy code.
Ex. 2.1
int global_num; //This is a global variable
void main()
{
display(); //call display function
}
void display()
{
int num2 = 2; //This is a local variable
//It can only be used in the "display()" function
num2 = global_num; //assign the global variable a value
}
The global variable "global_num" can be used in the "display" and any other function, like "main" for example. The local variable "num2" can only be used within the "display" function, so it would not work in any other function outside of its scope. Also,
Now you will see what importance the data types have in functions. The parenthesis "()" are there for a reason. They are used to pass local variables into other functions. The variables being passed into functions are called "arguments" or "parameters". The contents of the () is known as the parameter/argument list. Here is a prototype:
type function_name(argument_list);
The most important thing to remember is to always have the same number of arguments in the prototype, the call, and the header. The exception to this is when using overloaded functions which is described in section 4.
_______________________________________________________________________
The data type in front of the function name determines what type of variables that function will return. An int function will return an integer variable.
Ex. 3.1
Prototype: int triple_fun(int num3);
In the function prototype you can place any variables into the parameter list. The variable here acts as a local variable that are created solely to store the inputs to the function (num3 in the previous example).
Ex. 3.2
int num2 = 6;
triple_fun(num2);//function call
In the function call you may pass any variable of the same corresponding parameter type into the function. Here num2 is being passed into the function and num3 will receive its value.
Ex. 3.3
Header:
int triple_fun(int num3)
{
return num3 * 3;//return the input value tripled!
}
Notice that num3 has the data type before it in the argument list. That is because it is creating a local variable for the "triple_fun" function. num3 will take the value of whatever variable was passed into the function, in this case "num3" will become the value that "num2" was (see the call function above).
After the function has ended, use the return command to return whatever value is needed. The return value is the output of the function. The above example showed a function that would return triple its input value. See below for a 2nd example:
Ex. 3.4
#include <iostream.h>
int multiply(int first, int second); //prototype with 2 integer input arguments
void main()
{
//Local variables
int num1 = 0;
int num2 = 0;
int product;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter another number: ";
cin >> num2;
product = multiply(num1, num2); /*call: num1 and num2 are input arguments. Returned output is stored into "product"*/
cout << "\nThe product of the numbers is: "<<product<<"!"<<endl;
}
/*header with input arguments being passed into the locally defined variables "first" and "second" */
int multipy(int first, int second)
{
return (first * second);
/* Returning the product of the 2 inputs. Any variables can be assigned this returned output value*/
}
OUTPUT:
Enter a number: [6]
Enter another number: [4]
The product of the numbers is 24!
You can pass any 2 integer values into the function and "product" will receive their product.
Notice the purple highlight "product = multiply(...)". This is where "product" receives the value of the number being returned from the function.
NOTE: Returning a value causes the function to end. If you ever needed the function to break execution, you could return any value at any time.
Ex. 3.5
return -1;
Ex. 3.6
multiply(5,10); //call with "5" and "10" as input arguments
Here the returned value will be 50 because 5 and 10 were passed into the function. 5 and 10 are multiplied within the function and returned, so "product" receives that value.
______________________________________________________________________
Functions can have many arguments.
Ex. 3.7
Prototype: double get_data(int, double, int);//data-type list
Call:
get_data(id, price, quantity);//variables passed in
Header:
double get_data(int nId, double nPrice, int nQuantity)
Defined local variables that acquire the input values
To pass more than one variable just put commas between the variables, but make sure that there are always the same number of variables in each function prototype as in the call and the header. The variables must also be in the correct order each time. Overloaded functions can break this rule, but they will be explained in the next section.
______________________________________________________________________
If you don’t want to pass any variables into a function you can either:
-Leave the () empty, or
-Put a "void" in the ().
Ex. 3.8
void main()
or:
void main(void)
They both mean the same thing so it really doesn’t matter which you choose. Remember that "void" functions CAN NOT "return" a value.
______________________________________________________________________
Overloading is the ability to assign default values to any of the function parameters and not have to enter them in the call. The next example uses the same function as shown before, but uses default values in the prototype so that the user is not required to enter a value. If no value is entered for a variable, the default is assigned
Ex 3.9
Prototype:
double get_data(int nId = 1, double nPrice = 5.50, int nQuantity = 11);
Call:
get_data(id, price, quantity);//all variables passed in
Header:
double get_data(int nId, double nPrice, int nQuantity)
A default value was specified for each of the inputs in the function prototype (1, 5.50, 11 respectively). Thus none have to be specified in the function call, but may be if you choose to use values other than the default.
get_data(3);//only first variable passed in
get_data(id, 4.50);//only first 2 variables passed in
In both of these cases the 3rd parameter was given the default value of 11 while the others had customized values passed in.
NOTE: You may not skip variables, they must be passed consecutively. For example, if you want to specify the 3rd parameter, then you must also specify the 2nd parameter. The compiler assumes that the input parameters are entered consecutively.
Ex. 3.10
get_data(3, 12);//trying to enter the first and third parameter
//This will enter 12 for the 2nd parameter, not the desired result
get_data(3, 5.50, 12);/*first and third parameter. This works because the compiler
now understands that the 12 is meant for the third parameter.
The default of 5.50 had to be implicitly specified*/
Lastly, there is one more way to overload a function and it deals with creating multiple functions with the same name, but different parameter lists.
Here are 3 functions of the same name with differing parameter lists:
Ex. 3.11
double get_data(int nId);
double get_data(int nId, double nPrice);
double get_data(int nId, double nPrice, int nQuantity);
There must be 3 corresponding function bodies to accommodate these 3 prototypes, and each one can perform its own tasks differently if needed.
What will the following program do?
______________________________________________________________________
#include<iostream.h>
int sumup(int, int); //function prototype
void main()
{
int num1, num2, num3;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter another number: ";
cin >> num2;
cout << "Enter yet another number: ";
cin >> num3;
cout << "The sum of the three is "<<sumup(num1,num2,num3)<<"!"<<endl;
}//end main
int add(int add1, int add2, int add3) function header
{
int sum;
sum = add1 + add2 + add3;
return sum; //return value of sum
}
______________________________________________________________________
ANSWER:
Enter a number: [10]
Enter another number: [19]
Enter yet another number: [6]
The sum of the three is 35!
User input is represented with brackets [ ]
If you were able to understand that, you are still on track. If not, just keep practicing until it all makes more sense. Just remember the three things that a function needs: Function Prototype, Call Function, and a Function Header. Also understand that a function can have multiple inputs but only one output. Later I will explain referencing, in which the values don’t need to be returned but can be altered within the function.