07-26-2013, 02:26 PM
Introduction to functions
Hello there, and welcome to my tutorial on functions. I'll be covering how to declare a function, how to use one and examples of functions.First of all, what is a function?
Good question, Sir! A function is basically a block of code that performs a task. Functions are great because it helps you divide your code into smaller chunks that are easier to develop. We've already declared one function before. Yes, the main function.
How do we declare a function, sensei?
Oh, that is really easy. The form goes as follows:Hidden Content
Hard to understand? I'll show you a basic example of a function:
Hidden Content
What this does is that it counts the characters in the string and stores the number of characters in an integer variable. And then it returns the value. This concept might be a little hard to grasp at first, but You'll get the hang of it eventually. Just practise.
Now we need to call this function.
Sensei, tell us how to call the function please!
Yes, here's a complete example of the function I made.Hidden Content
This might be a little advanced for some, so I'll show you another example of a function that adds two numbers. It's really easy!
Hidden Content
So that should be the basics of functions! I'm sorry if this was too hard to understand. If you've got any questions, please ask me. I promise, Sensei never bites!
TIP: You won't learn this completely if you don't experiment with it. Try and make some functions yourself and see how it goes! If you're having problems, post a help thread in this forum section and I (and other forum members if they want) will try and help you as much as we can.
Useful additions by other members
0xDEADPIXEL:Hidden Content
The "void" keyword can also be used in the function's parameter list to specify that we don't want the function to take any actual parameters when it's called. The function SayHello() could have also been declared as:
Hidden Content
Although it is optional to use "void" in the parameter list of the function, leaving the parameter list blank will also result in a function that does not take any parameters.
If there's something I've done wrong that I haven't realized, please tell correct me. And by all means, if you've got something you'd like to add to the tutorial, reply on here and I'll add it to the thread.
Thank you![/hide]