Functions In C++

Topic asked in February 2022 (CBCS), December 2022 (CBCS) and May 2024 (NEP) question paper.

In C++, functions are blocks of code that perform a specific task. They encapsulate a set of statements that can be called and executed at different points in a program. They play a vital role in structuring programs, promoting modularity, reusability, and readability.

Defining A Function

To define a function in C++, you typically need to follow these steps:

  1. Specify the Return Type: Declare the return type of the function. It could be void if the function doesn't return any value, or any other data type if the function does return a value.

  2. Specify the Function Name: Give a name to your function. This name should be unique within its scope and should follow the rules for naming identifiers in C++.

  3. Specify the Parameter List (if any): If your function takes parameters, specify them inside parentheses after the function name. Parameters are variables that hold the values passed to the function when it is called.

  4. Write the Function Body: Define the body of the function inside curly braces . This is where you specify the actions that the function performs.

  5. Return a Value (if applicable): If your function is supposed to return a value, use the return statement followed by the value to be returned.

Here's a simple example of defining a function in C++:

#include <iostream>
using namespace std;
 
// Function definition
int add(int a, int b) {
    int sum = a + b;
    return sum;
}
 
int main() {
    int result = add(3, 4); // Function call
    cout << "The result is: " << result << endl;
    return 0;
}

Output:

The result is: 7

In this example:

  • We define a function named add that takes two integer parameters a and b.
  • Inside the function body, we calculate the sum of a and b and store it in a variable sum.
  • We return the value of sum using the return statement.
  • In the main() function, we call the add() function with arguments 3 and 4, and store the result in the variable result.
  • Finally, we print the result using cout.

You can define functions anywhere in your C++ program, but it's a good practice to declare them before they are used. This is typically done by providing a function prototype (also known as a function declaration) before the main() function or wherever the function is first used.

Function Prototype

A function prototype (also known as a function declaration) informs the compiler about the name of the function, its return type, and the types of its parameters. This allows the compiler to correctly process function calls before the actual function definition is encountered. Function prototypes are typically placed before the main() function or at the beginning of a code file.

Here's the syntax for a function prototype:

return_type function_name(parameter_type1, parameter_type2, ...)

For example, consider the add() function we've been using in previous examples:

int add(int a, int b); // Function prototype

In this prototype:

  • int is the return type of the function.
  • add is the name of the function.
  • (int a, int b) specifies the parameter list. It indicates that the add() function takes two int parameters named a and b.

Here's a complete example demonstrating the use of a function prototype:

#include <iostream>
using namespace std;
// Function prototype
int add(int a, int b);
 
int main() {
    int result = add(3, 4); // Function call
    cout << "The result is: " << result << endl;
    return 0;
}
 
// Function definition
int add(int a, int b) {
    int sum = a + b;
    return sum;
}

Output:

The result is: 7

In this example:

  • The function prototype for add() is provided before the main() function.
  • This allows the main() function to call add() before its actual definition.
  • Later in the code, the add() function is defined with the same signature as its prototype.

Invoking/Calling A Function

In C++, you invoke or call a function by using its name followed by parentheses (). If the function takes arguments, you provide them inside the parentheses. Here's a basic example:

#include <iostream>
using namespace std;
 
// Function definition
void greet() {
    cout << "Hello, Eniv" <<endl;
}
 
int main() {
    greet();     // Calling the function
    return 0;
}

Output:

Hello, Eniv

Returning Values from a Function

In C++, functions can return values using the return statement. The return type of the function should match the type specified in the function declaration or definition. Functions can have various return types, including void for functions that do not return a value, and non-void return types for functions that do return a value.

Non-Void Return Type

#include <iostream>
using namespace std;
 
// Function definition
int add(int a, int b) {
    return a + b;
}
 
int main() {
    // Calling the function and storing the returned value
    int sum = add(3, 4); 
    cout << "The sum is: " << sum <<endl;
    return 0;
}

Output:-

The sum is: 7

Explanation:

  • In the given example, we have a function named add() that takes two integers a and b as parameters and returns their sum using the return statement.
  • Inside the main() function, we call the add() function with arguments 3 and 4. The returned value (the sum of 3 and 4, which is 7) is stored in the variable sum.
  • Finally, we output the value of sum using cout.

Void Return Type

#include <iostream>
using namespace std;
 
// Function definition with a void return type
void greet() {
    cout << "Hello, Eniv" << endl;
}
 
int main() {
    // Calling the function
    greet(); 
    return 0;
}

Output:

Hello, Eniv

Explanation:

  • In this example, we have a function named greet() with a void return type. This function simply prints "Hello, Eniv" to the console.
  • Inside the main() function, we call the greet() function, which executes the code within the function body.
  • Since the greet() function has a void return type, it does not return any value.

Types Of Functions

In C++, functions can be broadly categorized into two main types: user-defined functions and library functions.

  1. Library Functions
    • These functions are provided by pre-existing libraries, such as the C++ Standard Library or third-party libraries.
    • They offer standardized functionality for various common tasks, ranging from input/output operations to complex mathematical calculations.
    #include <iostream>
    #include <cmath> // Including the <cmath> header for using library function (sqrt())
    using namespace std;
     
    int main() {
        float num = 25.0;
        float sqrt_result = sqrt(num); // sqrt() function calculates square root of number
        cout << "Square root of " << num << " is: " << sqrt_result << endl;
        return 0;
    }

Output:

Square root of 25 is: 5
  1. User-defined Functions
    • These functions are created by the programmer to perform specific tasks within their program.
    • They encapsulate a sequence of statements to perform a particular operation, and they can be designed to suit the specific needs of the program.
    #include <iostream>
    using namespace std;
     
    // User-defined function to add two numbers
    int add(int a, int b) {
        return a + b;
    }
     
    int main() {
        int num1 = 5, num2 = 3;
        int sum = add(num1, num2); // Calling the user-defined function
        cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;
        return 0;
    }

Output:

The sum of 5 and 3 is: 8

Call by Value

In call by value, a copy of the argument is passed to the function. Any changes made to the parameter inside the function do not affect the original argument. Here's an example:

#include <iostream>
using namespace std;
 
void increment(int x) {
    x++;
    cout << "Inside function: " << x << endl;
}
 
int main() {
    int num = 5;
    // Calling the function
    increment(num); 
    cout << "Outside function: " << num << endl;
    return 0;
}

Output:

Inside function: 6
Outside function: 5

Explanation:

  • Inside the increment() function, the parameter x receives a copy of the value of num, which is 5.
  • Inside the function, x is incremented to 6, but this change does not affect the original variable num outside the function.
  • Outside the function, the value of num remains 5.

Call by Reference

In call by reference, a reference to the argument is passed to the function. Changes made to the parameter inside the function affect the original argument. Here's an example:

#include <iostream>
using namespace std;
 
// Function definition for call by reference
void increment(int &x) {
    x++;
    cout << "Inside function: " << x << endl;
}
 
int main() {
    int num = 5;
    // Calling the function by reference
    increment(num); 
    cout << "Outside function: " << num << endl;
    return 0;
}

Output:

Inside function: 6
Outside function: 6

Explanation:

  • Inside the increment() function, the parameter x is a reference to the variable num.
  • When x is incremented inside the function, it directly affects the original variable num outside the function.
  • Hence, both inside and outside the function, the value of num becomes 6 after the function call.

Difference between Call By Value and Call By Reference

Topic asked in July 2022 (CBCS) and May 2024 (NEP) question paper.

Parameter PassingCall by ValueCall by Reference
Effect on Actual ArgumentUnchangedPotentially Modified
Modification of Formal ParameterNo effect on actual parameterPotential modification of actual parameter
Memory UsageAdditional memory may be allocated for local variablesNo additional memory allocated, operates directly on actual parameter
PerformanceMay be slower due to copying of valuesGenerally faster due to direct access to memory
Use CaseWhen you don't want the actual argument to be modifiedWhen you want to modify the actual argument or want to save memory and time

Scope rules

Topic asked in December 2022 (CBCS) question paper.

Scope rules in C++ define the visibility and accessibility of identifiers, such as variables and functions within a program. Understanding scope rules is crucial for writing organized, modular, and bug-free code.

Local Variables

Local variables are defined within a block, such as a function, loop, or conditional statement. They have limited visibility and are accessible only within the block where they are declared. Once the block is exited, local variables are destroyed, and their memory is deallocated. Local variables take precedence over global variables with the same name within the same scope.

Example:

#include <iostream>
using namespace std;
 
void myFunction() {
    int localVar = 10; // Local variable
    cout << "Inside myFunction(): localVar = " << localVar << endl;
}
 
int main() {
    myFunction(); // Attempting to access localVar here will result in an error
    return 0;
}

Output Explanation:

  • The myFunction() is called from the main() function.
  • Inside myFunction(), a local variable localVar is declared and initialized to 10.
  • The value of localVar is then printed within myFunction().
  • After myFunction() finishes executing, the local variable localVar goes out of scope and is destroyed.
  • Attempting to access localVar outside of myFunction() in main() will result in a compilation error because localVar is not accessible outside of its scope.

Example:-

int main() {
    myFunction();
    cout << "Attempting to access localVar in main(): " << localVar << endl; // Error: localVar is not accessible here
    return 0;
}

It will result in error.

Global Variables

Global variables are declared outside of all functions, usually at the beginning of the file or in a header file. They have a global scope, meaning they are accessible from anywhere in the program. Global variables persist throughout the program's execution and are not destroyed until the program terminates. It's generally advised to minimize the use of global variables to avoid unintended side effects and improve code maintainability.

Example:

#include <iostream>
using namespace std;
 
// Global variable
int globalVar = 20;
 
void myFunction() {
    cout << "Inside myFunction(): globalVar = " << globalVar << endl;
}
 
int main() {
    cout << "Inside main(): globalVar = " << globalVar << endl;
    myFunction();
    return 0;
}

Output Explanation:

  • The global variable globalVar is declared outside of any function, making it accessible from anywhere in the program.
  • Inside the main() function, the value of globalVar is printed.
  • The myFunction() is then called, which also prints the value of globalVar.
  • Both outputs show the value of globalVar, which is 20, demonstrating that global variables are accessible from any part of the program.

Scope Rules of Functions

Functions also have their own scope. Functions declared at global scope are accessible from anywhere in the program, while functions declared within other functions have a local scope and are only accessible within the enclosing function. Unlike some other programming languages, C++ does not support nested functions (functions declared inside other functions). However, functions can call each other, and local variables declared within a function are accessible only within that function.

Example 1: Error due to Nested Function (Illegal in C++)

#include <iostream>
using namespace std;
 
void outerFunction() {
    cout << "Inside outerFunction()" << endl;
    
    void innerFunction() { // Nested function - illegal in C++
        cout << "Inside innerFunction()" << endl;
    }
 
    innerFunction(); // Call to innerFunction()
}
 
int main() {
    outerFunction();
    // Attempting to call innerFunction() here will result in an error
    return 0;
}

Output Explanation:

  • The outerFunction() is called from the main() function.
  • Inside outerFunction(), an attempt is made to declare a nested function innerFunction(), which is illegal in C++. C++ does not support nested functions.
  • Therefore, attempting to call innerFunction() inside outerFunction() will result in a compilation error.
  • The program fails to compile due to the illegal attempt to define a nested function.

Example 2: Function Call from Main Function (No Error)

#include <iostream>
using namespace std;
 
void myFunction() {
    cout << "Inside myFunction(): This function can be called from main()" << endl;
}
 
int main() {
    cout << "Inside main(): Calling myFunction()" << endl;
    myFunction();
    return 0;
}

Output:

Inside main(): Calling myFunction()
Inside myFunction(): This function can be called from main()

Output Explanation:

  • The myFunction() is defined separately from the main() function.
  • Inside main(), myFunction() is called, and the output of myFunction() is printed.
  • There are no scope-related errors in this example because myFunction() is defined in a global scope and can be accessed from any part of the program.
How's article quality?

Last updated on -

Page Contents