Functions in C++

COS1511 - Introduction To Programming I · Learning C++

Functions in C++

A function in C++ is a block of code that performs a specific task. Functions help you to organise your code into reusable sections. You can call a function whenever you need to execute the code inside it, which makes your program easier to read and maintain.

Defining a Function

To define a function in C++, you need to specify the return type, the function name, and any parameters it takes. The general syntax is as follows:

return_type function_name(parameter_type parameter_name) {

Here is a simple example of a function that adds two integers:

int add(int a, int b) {

The function add takes two parameters, a and b, both of type int. It will return their sum.

    return a + b;

To complete the function definition:

}

This function can be called in your main program to perform the addition.

Calling a Function

To call a function, simply use its name and provide the required arguments. Here is how you can call the add function:

int main() {
    int result = add(5, 3); // Calls the add function
    return 0;
}

In this example, the function add is called with the arguments 5 and 3. The result will be stored in the variable result.

Remember: The data types of the arguments you pass to the function must match the parameter types defined in the function.

Function Return Values

A function can return a value to the part of the program that called it. The return type specified in the function definition indicates what type of value the function will return. If a function does not return a value, you should use void as the return type.

For example, here is a function that returns the maximum of two integers:

int max(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

In this case, the function max returns the larger of the two integers provided as arguments.

Function Parameters

Parameters are the variables used in a function definition. They act as placeholders for the values that will be passed to the function when it is called. You can define multiple parameters by separating them with commas.

For example:

void printSum(int a, int b) {
    int sum = a + b;
    std::cout << "Sum: " << sum << std::endl;
}

This function does not return a value, as indicated by the void return type. It simply prints the sum of the two integers.

Default Parameters

You can provide default values for parameters in C++. If a caller does not provide an argument for a parameter with a default value, the default value will be used. Here is an example:

void greet(std::string name = "Guest") {
    std::cout << "Hello, " << name << "!" << std::endl;
}

In this case, if you call greet() without an argument, it will print "Hello, Guest!". If you call greet("Alice"), it will print "Hello, Alice!".

Tip: Use default parameters to make your functions more flexible.

Variable Scope

Variable scope refers to the visibility of a variable within different parts of your program. Variables defined inside a function are local to that function. They cannot be accessed outside of it. For example:

void myFunction() {
    int localVar = 10; // Local variable
}

The variable localVar cannot be accessed in main or any other function.

Function Overloading

C++ allows you to define multiple functions with the same name, provided they have different parameter types or numbers. This is called function overloading. Here is an example:

int multiply(int a, int b) {
    return a * b;
}
double multiply(double a, double b) {
    return a * b;

In this case, there are two multiply functions: one for integers and one for doubles. The correct function will be called based on the argument types provided.

Watch out: Ensure that the function signatures (name and parameter types) are different; otherwise, the compiler will not know which function to call.

Inline Functions

Inline functions are a way to suggest to the compiler to insert the function's code directly into the calling code, rather than using the usual function call mechanism. This can improve performance for small, frequently called functions. To define an inline function, use the inline keyword:

inline int square(int x) {
    return x * x;
}

However, the compiler may ignore this suggestion if it deems it inappropriate.

Recursion

Recursion is when a function calls itself. This can be useful for solving problems that can be broken down into smaller, similar problems. A classic example is calculating the factorial of a number:

int factorial(int n) {
    if (n <= 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

In this example, the function factorial calls itself with a decremented value of n until it reaches the base case of n <= 1.

Conclusion

Functions are a fundamental part of programming in C++. They help you to write modular and reusable code. Understanding how to define, call, and use functions effectively is crucial for developing efficient programs.

Summary

  • A function is a block of code that performs a specific task.
  • Functions can take parameters and return values.
  • Default parameters allow for flexibility in function calls.
  • Variable scope determines where a variable can be accessed.
  • Function overloading allows multiple functions to have the same name with different parameters.
  • Recursion is when a function calls itself.

Check your understanding

  1. What is the syntax for defining a function in C++?
  2. How do you call a function with parameters?
  3. What is the difference between local and global variables?
  4. Explain how function overloading works in C++.