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:
-
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.
-
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++.
-
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.
-
Write the Function Body: Define the body of the function inside curly braces . This is where you specify the actions that the function performs.
-
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++:
Output:
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:
For example, consider the add() function we've been using in previous examples:
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:
Output:
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:
Output:
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
Output:-
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
Output:
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.
- 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.
Output:
- 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.
Output:
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:
Output:
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:
Output:
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 Passing | Call by Value | Call by Reference |
---|---|---|
Effect on Actual Argument | Unchanged | Potentially Modified |
Modification of Formal Parameter | No effect on actual parameter | Potential modification of actual parameter |
Memory Usage | Additional memory may be allocated for local variables | No additional memory allocated, operates directly on actual parameter |
Performance | May be slower due to copying of values | Generally faster due to direct access to memory |
Use Case | When you don't want the actual argument to be modified | When 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:
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:-
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:
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++)
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)
Output:
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.
Last updated on -