Welcome Guest [Log In] [Register]
We hope you enjoy your visit.


You're currently viewing the Ultimate 3D Community as a guest. This means that you can only read posts, but can not create posts or topics by yourself. To be able to post you need to register. Then you can participate in the community active and use many member-only features such as customizing your profile, sending personal messages, and voting in polls. Registration is simple, fast, and completely free.

Join our community!

If you are already a member please log in to your account to access all of our features:

Username:   Password:
Add Reply
Getting Started with Functions; How to make and start using functions
Topic Started: Aug 10 2008, 06:25 PM (383 Views)
Gandalf20000
Member Avatar
Geek
[ *  *  *  *  *  * ]
You've made your first C++ program. You managed to get the system to create a little DOS window that says, "I'm a C++ program!" or something like that.
But, you want to move on to harder stuff and learn some more. You read up about functions, but you can't understand what the crap the tutorial is saying.

That is where this tutorial comes in.

You've seen that little "main(blahblahblah)" thing you write in every C++ program. That is a function.
However, that function simply is used to make the program usable.
Here is how you make a function in C++:
Code:
 

int doubleNumber(void)
{
//Create the variable needed
int numberToDouble=0;

//Tell the system to tell you to enter an integer
cout << "Please enter an integer you want doubled. ";
//Receive the user input and set numberToDouble to that value.
cin >> numberToDouble;

//Add numberToDouble to itself to get the value.
finalNumber=(numberToDouble+numberToDouble);

//Return the number so you can use it.
return finalNumber;
}


Okay. Now you've written a function. But how on earth do you use it?!
First of all, you create the function in a separate header file or before main() is initiated.
Second of all, you use it like this in the main() function:
Code:
 

int main(void)
{
//Print the introduction on screen
cout << "This program will double a number of your choice.\n"

//Use the function doubleNumber()
int numberDoubled=doubleNumber()

//Print the new number on screen.
cout << "Here is the integer squared: "
<< numberDoubled
<< "\n"
<< endl;

//Make sure you see the end result.
system("PAUSE")
return 0
}


And now you (hopefully) know how to make C++ functions.

For a source file I made using functions:
C++ Functions

This file has some stuff that wasn't mentioned in the tutorial, but it is commented, and will hopefully help you learn.
Offline Profile Quote Post Goto Top
 
« Previous Topic · Tutorials · Next Topic »
Add Reply