C Functions
A function is a set of statements that take inputs, do some specific computation and produces output. You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the Code once, and use it many times.
Types of Functions
There are two types of functions in C programming:
- Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
- User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.
Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header and a function body.
Parts of a function
- Return Type − A return_type function may return a value.
- Function Name − The function name and the parameter list together constitute the function signature.
- Parameters − When a function is invoked, you pass a value to the parameter. The parameter list refers to the type, order, and number of the parameters of a function.
- Function Body − The function body contains a collection of statements that define what the function does.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function −
Sr.No | Call Type & Description |
---|---|
1 | Call by value: This method copies the actual value of an argument into the formal parameter of the function. |
2 | Call by reference: This method copies the address of an argument into the formal parameter. |
Create a Function
To create (often referred to as declare) your own function, specify the name of the function, followed by parentheses () and curly brackets {}:
void myFunction() {
// code to be executed
}
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.