A function is a group of code (programming statements) specified to perform a particular task. A function must have a name and the code associated with the function is executed when it is called. It is used when a particular code is to be used many times in the same program. Instead of doing this, a function is made with that code and is called where it is needed.
A function needs to be called explicitly by the programmer (except the constructors and the main function).
Prototyping: Prototyping is telling the compiler about the function, the number and type of arguments passed etc. to the compiler.
Syntax: returntype functionname(datatype [formal arguments]); -optional
eg.- int add(int, int);
Definition: Defining the function means specifying the tasks that a particular function will perform. The coding of function is done in the definition part.
eg- int add(int x, int y)
Calling: To call a function, a calling statement must be generated. The call must be within another function or procedure.
c=sum(a,b); //Calling Statement
Passing arguments to functions:-Functions can be called by three types-
1. Call by Value– In call by value, the value of variable itself is passed.
Calling– function(int a);
Any changes made to the variable in the function will not reflect outside the scope of that function.
2. Call by pointer– In call by pointer, the address of the variable is passed.
Prototyping- function(datatype *);
Calling- function(int &a);
The address of ‘a’ is passed and formal arguments catches that address.
Any changes made to the variable in the function are reflected outside the scope of the function as the changes are made to that specific address.
3. Call by reference– This is a special type of calling introduced in C++ and is unavailable in C. In call by reference, an alias of the variable passed is made referring to the same memory location.
Calling- function(int a);
Since an alias is created, so the changes made to any of the variables will always reflect in the other variable.