What Is a Function in Programming? | MakeUseOf

Do you often find yourself copying and pasting your code to reuse in different sections in your program?

If so, you might want to consider using functions. Functions are a very powerful feature of programming languages. They can make code more efficient, easier to read, and elegant.

What Is A Function?

A function is a block of code that performs a task. It can be called and reused multiple times. You can pass information to a function and it can send information back. Many programming languages have built-in functions that you can access in their library, but you can also create your own functions.

When you call a function, the program will pause the current program and execute the function. The function will be read from top to bottom. Once the function is complete, The program continues to run where it had paused. If the function returned a value, that value will be used where the function was called.

How Do You Write A Function?

There are many different ways to write functions. The exact syntax will depend on the language that you are programming in. We will show examples in Python, JavaScript, and C++ to demonstrate a range of programming syntax.

Related: Why Programming Languages Can’t Exist Without Functions

Void Functions

The first type of function that we will look at is a void function. This simply means that the function does not return a value. Void functions are used to complete a set of instructions. In these examples, the function we wrote is called helloFunction. The purpose of the function is to output “Hello World”.

TIP: give functions names that explain what they do. It will be easier to manage functions and read the code as your program becomes more complex.

Python

def helloFunction():
print("Hello World")
helloFunction()

The keyword def is used in Python to define and create a function. Next, is the name of the function. The instructions in the function follow on the next line after the colon. White space matters in Python, so be sure to indent all the code that you want your function to run. In the example above, the function runs one line of code.

Your keen eyes might have noticed that print() is also a function, but it is called differently than our function. Hold on to that thought right now, we will explore functions will parameters later.

JavaScript

function helloFunction(){
alert("Hello World!");
}
helloFunction();

In JavaScript, the keyword function is used to create functions. Next, we have the name of the function. Any code that falls between the curly brackets is run when the function is called.

White space is not important in JavaScript, but it is customary to indent the code in the function. Indentation makes code easier to read, which is very important as your programs become more complex.

Note: Much like print() in the earlier example, alert() is also a function.

C++

#include 
using namespace std;
void helloFunction(){
cout }
int main(){
helloFunction();
return 0;
}

Functions are created differently in C++. Instead of a keyword to define a function, the first word describes the type of data that the function will return. In this case, our function does not return any data, so the data is void. Next, we have the function’s name. Similar to JavaScript, all the code between the curly brackets is run when the function is called. Also similarly to JavaScript, white space does not affect the function but is good practice.

Did you spot another function in the C++ code? Yes, main() is a function. When you execute a C++ program, you automatically call the main function. When the main function is successfully completed, it returns 0 as it exits the program to signal there were no errors running the program.

Functions That Require Values

Void functions are great if you find that you are writing the same bit of code over and over again. But they can be limiting. They are static and don’t change. They always complete the same instructions. One way we can increase their usefulness is to pass different values to the function.

You will have noticed that brackets followed the names of all of our functions. In the brackets, we can declare that data is needed to run our function. Then we can use the data passed to our function in the function. Let’s take a look at the previous examples again, but this time pass the phrase that we want to be outputted.

Python

def helloFunction(newPhrase):
print(newPhrase)
helloFunction("Our new phrase")

Now, between the brackets, our function declares that it needs a variable to run. We have named the variable newPhrase and can now use it in our function. When we call the function, we need to pass the requested information by placing it in between the brackets. The same changes were made in JavaScript.

JavaScript

function helloFunction(newPhrase){
alert(newPhrase);
}
helloFunction("Our new phrase");

C++

#include 
using namespace std;
void helloFunction(string newPhrase){
cout }
int main(){
helloFunction("Our new Phrase");
return 0;
}

Our C++ function required a bit more information. We know that your function wants string data, but that’s not good enough for C++. When you create your function you have to specify what type of data your function requires. If you do not send the correct type of data, the function will create an error.

This might seem a little annoying, but strict languages can often save you headaches. If you write a function in JavaScript that requires an integer, but the number is sent as a string, it can create a bug that is very hard to track down.

Related: 5 Functional Programming Languages You Should Know

Functions That Return a Value

The final function ability that we will cover is returning data. This is particularly valuable when you want to alter data before you use it. Although you could write that inline, if you will use the same calculations many times, like converting imperial to metric, it might make more sense to write it as a function. Our example will be simpler. Our function will require two integers and will return the sum.

Python

def addingFunction(a, b):
return a + b
print(addingFunction(2, 4))

In this example, our function requires two variables instead of one. We indicate that by separating our variable names with a comma. The keyword return tells the function to return the following data, in this case, 2 + 4, or 6. We call the function inside the print() function.

Once our program got to that line, it would have paused, ran our function, and then continued as if addingFunction(2, 4) was actually just the returned value 6.

JavaScript

The JavaScript code is very similar to the Python code. The primary difference is that the function is called in an alert.

function addingFunction(a, b){
return a + b;
}
alert(addingFunction(2, 4));

C++

#include 
using namespace std;
int addingFunction(int a, int b){
return a + b;
}
int main(){
cout return 0;
}

The C++ code runs similarly, but as usual, requires a bit more information. First, we have to say what type of data our function will return. You will see that void has been changed to int. This means that instead of returning no data, our function will return an integer. Beyond that, the code is similar to the code we have already explored.

Manage Your Functions

A fun thing about functions is that functions can call other functions. They can even call themselves! But with great power comes great responsibility. Do not go crazy creating code with functions that call other functions that call yet more functions.

As mentioned, every time a function is called, the program pauses while it runs the function. This means that the program is being held in active memory. If you call several more functions without completing them, you are using more active memory. If you are not careful, your program can get out of hand.

Source: makeuseof.com

Related posts

These Are the Most Important Components for Your Gaming PC

Ugreen Nexode Pro 160W GaN Fast Charger Review: So Much Power in a Small Package

Using AI to Create Logos: The Pros, Cons, and Best Practices