Subroutines Definition Types and Examples in C
Subroutines Definition Types and Examples in C
Definition
In C++, a subroutine is typically defined using the void keyword for procedures and a return type
for functions. The syntax is as follows:
C++
return_type function_name(parameter_list) {
// Function body
}
● return_type: Specifies the data type of the value returned by the function. If the function
doesn't return a value, use void.
● function_name: A unique identifier for the subroutine.
● parameter_list: A comma-separated list of parameters (variables) that the function receives
from the caller.
1. Functions:
○ Return a value.
○ Used for calculations, data retrieval, and other tasks that produce results.
○ Example:
C++
int calculate_area(int length, int width) {
return length * width;
}
● Parameters: Variables declared within the subroutine's parentheses to receive values from
the caller.
● Arguments: Actual values passed to the subroutine when it's called.
● Example:
C++
void greet(std::string name) { // name is a parameter
std::cout << "Hello, " << name << "!" << std::endl;
}
Scope of Variables
● Local variables: Declared within a subroutine, accessible only within that subroutine.
● Global variables: Declared outside subroutines, accessible from anywhere in the program.
● Example:
C++
int global_var = 10;
void my_function() {
int local_var = 5;
std::cout << global_var << std::endl; // Accesses global
variable
// std::cout << local_var << std::endl; // Would cause an error
if used outside the function
}
Recursion
By following these guidelines, you can effectively write well-structured and maintainable code
using subroutines in C++.