Skip to main content

Command Palette

Search for a command to run...

Functions in C++

Published
•6 min read•View as Markdown
Functions in C++

A function is a block of code that runs when it is called.

In C++, the basic syntax for defining a function is as follows:

return_type function_name(parameter_list) {
    // body of the function
}
  • return_type: The data type of the value the function returns. Use void if the function does not return a value.

  • function_name: The name of the function.

  • parameter_list: A comma-separated list of parameters (optional), each defined by a data type and a name.

  • body of the function: The block of code that defines what the function does.

Void function:

A void function does not return any value. It performs a task but does not provide any output to the part of the program that called it.

#include <iostream>
using namespace std;

void sayHello() {
    cout << "Hello!" << endl;
}

void assistant() {
    sayHello();  // calling another function
    cout << "Work done!" << endl;
}

int main() {
    assistant();  // calling function
    return 0;
}

Forward declaration:

Forward declaration is a declaration of a function that tells the compiler about the function’s name, return type, and parameters (if any) before its actual definition (body) appears in the code.

#include <iostream>
using namespace std;

void sayHello();  // Function Declaration

int main() {
    sayHello();    // Calling function
    return 0;
}

void sayHello() {  // Function Definition
    cout << "Hello!" << endl;
}

Explanation: • void sayHello(); → Declaration (prototype)

• void sayHello() { ... } → Definition (body of the function)

• The function sayHello() is called inside main().

Just a small note for you:

*****If a function is defined after the main() function, then it must be declared before main() to avoid compiler errors.*****

Function with parameters:

Syntax:

#include <iostream>
using namespace std;

void sayHello();  // Function Declaration

int main() {
    sayHello();    // Calling function
    return 0;
}

void sayHello() {  // Function Definition
    cout << "Hello!" << endl;
}

Explanation:

• void sayHello(); → Declaration (prototype)

• void sayHello() { ... } → Definition (body of the function)

• The function sayHello() is called inside main().

If a function is defined after the main() function, then it must be declared before main() to avoid compiler errors.

return_type function_name(type param1, type param2) {

// Do some work

return some_value;

return zero;

}

Function syntax with parameters in C++:

return_type function_name(type param1, type param2) {

// Do some work

return someValue;

}

» Function to add two numbers:

The program is a simple C++ program that calculates the sum of two integers and prints the result.

#include <iostream>
using namespace std;

int sum(int a, int b) {
    return a + b;
}

int main() {
    int result = sum(5, 7);
    cout << "Sum is: " << result << endl;
    return 0;
}

»Function to multiply two numbers:

The program calculates the product of two integers and prints the result as a float.

#include <iostream>
using namespace std;

float product(int x, int y) {
    return static_cast<float>(x * y);
}

int main() {
    float result = product(61, 32);
    cout << "Result: " << result << endl;
    return 0;
}

» Write a function to check even or odd:

The function provided checks if a number is even and prints "true" or "false" accordingly.

#include <iostream>
using namespace std;

bool isEven(int n) {
    return n % 2 == 0;
}

int main() {
    int number = 4; // Example number
    if (isEven(number)) {
        cout << "true"; // even
    } else {
        cout << "false"; // odd
    }
    return 0;
}

» Write a function to print the factorial:

The program calculates and prints the factorial of a given number.

#include <iostream>
using namespace std;

int factorial(int n) {
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

int main() {
    int number = 6; // Example number
    int result = factorial(number);
    cout << "Factorial(" << number << ") = " << result << endl;
    return 0;
}

» Stack memory:

Concept:

When the execution of a program starts, the main function occupies its space in the stack memory including:

• Its parameters • Variables, etc.

🔹 Function Call Behavior:

Another function in the program (e.g., sum function) also allocates its space in the stack memory and occupies it:

• The upper memory is used.

• Parameters and local variables are included.

But due to the declaration of return, the value of sum comes back to the main function — this is called return of control.

➡ Then the space occupied in stack memory by the sum function is freed.

🔹 Key Points:

• Since the upper function is cleared in memory, it can be occupied by any other function called by the main function.

• Once the main function returns zero, it is also removed from the stack and the stack memory becomes unoccupied.

»Scope:

Area where a variable can be accessed or used.

::Local variable:

Those variables that are defined within the function cannot be used outside the function.

• Example Scopes:

• Loops: for (i, j)

• If conditions: if (..)

• Function blocks: { ... }

:: Global Scope

A variable that is defined outside the function and can be accessed globally by any function in the program.

#include <iostream>
using namespace std;

// Global variable declaration
int num = 25;

// Function to calculate the sum of two integers
int sum(int a, int b) {
    // Print the global variable
    cout << num << endl;
    // Return the sum of the two parameters
    return a + b;
}

int main() {
    // Call the sum function and store the result
    int s = sum(2, 6);
    // Print the global variable again
    cout << num << endl;
    // Return 0 to indicate successful execution
    return 0;
}

»Function overloading:

Multiple functions with the same name but different parameters.

Here's an example of function overloading in C++:

#include <iostream>
using namespace std;

// Function to add two integers
int add(int a, int b) {
    return a + b;
}

// Overloaded function to add two double values
double add(double a, double b) {
    return a + b;
}

// Overloaded function to add three integers
int add(int a, int b, int c) {
    return a + b + c;
}

int main() {
    // Calling the integer addition function
    cout << "Sum of 3 and 4: " << add(3, 4) << endl;

    // Calling the double addition function
    cout << "Sum of 3.5 and 4.5: " << add(3.5, 4.5) << endl;

    // Calling the three-integer addition function
    cout << "Sum of 1, 2, and 3: " << add(1, 2, 3) << endl;

    return 0;
}

Thanks for reading!!