Functions in C++ are a fundamental building block of the language, providing a way to organize and structure your code. They allow you to break down complex tasks into smaller, more manageable pieces, making your code more readable and maintainable. In this blog post, we will explore the different aspects of functions in C++, including function declaration, arguments, return values.
A function in C++ is defined by its name, return type, and the types and names of its parameters. The general syntax for a function declaration is as follows:
return_type function_name(parameter_type1 parameter_name1, parameter_type2 parameter_name2, ...) {
// function body
}
The return type is the data type of the value that the function returns. If the function does not return a value, the return type is "void." The parameter types and names are optional, but if a function requires input, the parameters must be specified. For example, the following function takes two integers as input and returns their sum:
int add(int a, int b) {
return a + b;
}
Function Arguments
When a function is called, the values passed to it are known as arguments. The types of the arguments must match the types of the parameters in the function declaration. There are two ways to pass arguments to a function in C++: by value and by reference.
Function call by value
Whenever we called a function and passed values of variable to the called function, such function is called as ‘call by value’, with this method, changes made to the parameter of the function have no effect on the variable in the calling function.
Eg.
#include<iostream>
using namespace std;
int main(){
int a=5,b=10,x,y;
void swap(int,int);
swap(a,b);
}
void swap(int a,int b){
int c;
c=a;
a=b;
b=c;
cout<<"a="<<a<<"b"<<b;
}
Function call by reference
Call by reference is method in which the address of each argument is passed to the function. By this method, the changes to the parameters of the function will affect the variable in the calling function.
Eg.
#include<iostream>
using namespace std;
int main(){
int a=5,b=10;
void swap(int*,int*);
swap(&a,&b);
cout<<"a="<<a<<"b="<<b;
}
void swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}
Functions can also be overloaded, which means that you can have multiple functions with the same name, but with different parameters. This allows for more flexibility and reusability in your code.
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
In this example, there are two "add" functions, one for integers and one for doubles.
In conclusion, functions in C++ are a powerful tool that can help you write more organized, readable, and maintainable code. Understanding how to pass arguments by value and by reference, and how to return values from a function, are key concepts that will help you use functions effectively in your C++ programs.