I was wondering how to create my own functions i read tutorials and i read it in my book but neither of them make sence to me if anyone on cprogramming could help please please do
I was wondering how to create my own functions i read tutorials and i read it in my book but neither of them make sence to me if anyone on cprogramming could help please please do
"Be Quick Or Be Dead"
[img]
http://www.danasoft.com/sig/GU.jpg
[/img]
The following is what I wrote in a thread a few days ago:
Here is an example of a function that happens to return nothing (void). I'd suggest learning each concept with a very simple program before applying it to your larger, more complicated program.Notice how the function is declared (see the prototype) before main(). Then it is called inside main(). And finally it is defined after main(). Make sure you are declaring and calling your text function correctly in addition to defining it.Code:#include <iostream> // Function prototype goes here above main(). void Display(int numToDisplay); int main() { int myNum = 0; // Pass any data that is needed by the function. Display(myNum); // Pass a local variable. Display(myNum+1); // Pass the result of an expression. Display(2); // Pass a constant value. Display(-1); // Pass a constant value. myNum = 3; // Change the local variable. Display(myNum); // Pass the modified variable. return 0; } // Function definition. Note it is the same as it was prototyped earlier. void Display(int numToDisplay) { // We now have a copy of the passed in data to use in the function. if (numToDisplay < 0) { std::cout << "Error, " << numToDisplay << " is invalid input." << std::endl; } else { std::cout << "Number is " << numToDisplay << std::endl; // Modifying numToDisplay does not change main()'s version. numToDisplay = numToDisplay * numToDisplay; std::cout << "Number squared is " << numToDisplay << std::endl; } }
Also notice how you have to pass the data to the function so that the function can use it. The function cannot use a variable that is declared inside a different function. For example, Display cannot use myNum because myNum was declared in main(). Instead, a copy of myNum's value must be passed to the Display function so that it can be used.
Does that help?
cool thanks
"Be Quick Or Be Dead"
[img]
http://www.danasoft.com/sig/GU.jpg
[/img]