OverIQ.com

Actual and Formal arguments in C

Last updated on July 27, 2020


Actual arguments #

Arguments which are mentioned in the function call is known as the actual argument. For example:

func1(12, 23);

here 12 and 23 are actual arguments.

Actual arguments can be constant, variables, expressions etc.

1
2
func1(a, b); // here actual arguments are variable
func1(a + b, b + a); // here actual arguments are expression

Formal Arguments #

Arguments which are mentioned in the definition of the function is called formal arguments. Formal arguments are very similar to local variables inside the function. Just like local variables, formal arguments are destroyed when the function ends.

1
2
3
4
int factorial(int n)
{
    // write logic here
}

Here n is the formal argument. Things to remember about actual and formal arguments.

  1. Order, number, and type of the actual arguments in the function call must match with formal arguments of the function.
  2. If there is type mismatch between actual and formal arguments then the compiler will try to convert the type of actual arguments to formal arguments if it is legal, Otherwise, a garbage value will be passed to the formal argument.
  3. Changes made in the formal argument do not affect the actual arguments.

The following program demonstrates this behaviour.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<stdio.h>
void func_1(int);

int main()
{
    int x = 10;

    printf("Before function call\n");
    printf("x = %d\n", x);

    func_1(x);

    printf("After function call\n");
    printf("x = %d\n", x);

    // signal to operating system program ran fine
    return 0;
}

void func_1(int a)
{
    a += 1;
    a++;
    printf("\na = %d\n\n", a);
}

Here the value of variable x is 10 before the function func_1() is called, after func_1() is called, the value of x inside main() is still 10. The changes made inside the function func_1() doesn't affect the value of x. This happens because when we pass values to the functions, a copy of the value is made and that copy is passed to the formal arguments. Hence Formal arguments work on a copy of the original value, not the original value itself, that's why changes made inside func_1() is not reflected inside main(). This process is known as passing arguments using Call by Value, we will discuss this concept in more detail in upcoming chapters.