» Intro to Functions by mochman |
|
(Login to remove green text ads)
Here is an introduction to creating and using functions in C++.
Code:
#include<iostream.h>
#include<conio.h>
//Function Prototype
int ourFunction( int );
int main(void) {
int userInput = 0;
// get a value from the user
cout << "Please enter an integer :";
cin >> userInput;
// just to see the difference we will output the old value
cout << "The old value is " << userInput << endl;
// the function is being called here
// you can also make a new variable and have it = ourFunction( userInput )
cout << "The new value is " << ourFunction( userInput ) << endl;
//Wait for a user to press any key to continue
getch();
return 0;
}
// Now the function is created
// the function will return an int
// and take in an int called valueIn
int ourFunction( int valueIn ) {
cout << "being changed to ";
valueIn = valueIn * 2;
return valueIn;
}
To start off, we will first need to create a prototype for the function we are making, this is usualy placed at the top of the file right around the #includes. The prototpye shows what values are passed in and if any values are returned from it.
int ourFunction( int )
(int #1) If the function is going to return a value, the type is here, if the function isn't going to return a value, "void" will be here instead.
(int #2) Values being passed in, multiple values can be separated by commas.
int ourFunction( int valueIn ) {
The function is then placed at the end of the file. The syntax for that is the same as the prototype with a variable names for the passed in values. This is then followed by a "{" to start the function.
The function is then coded, in our case our function tells the user that we are modifying the data, then we double the inputted value. After that we return it, so that our main function can use it.
Don't forget to close the function off with a "}" or the compiler will yell at you.
|
|