Passing Values between Functions

Passing Values between Functions

What is a function?

It’s a block of statements that are written to perform a specific task. A program is a collection of functions.

Like a human is not able to do all his task himself. Sometimes he need to call a mechanic, sometimes a doctor and many others. Similarly a computer program cannot handle all the tasks itself, it calls different functions to perform different tasks.

There are two types of functions in C;

  • Library functions
  • User defined functions

Library functions are the functions already defined in C library. We just need to include the respective header file and then we can use all the functions from that header file. Examples are printf(), scanf() etc.

User defined functions are those which are made by users, depending on their requirements.

Parts of User-Defined function:

Let’s observe the following code;

The highlighted lines demonstrates the parts of user defined functions.

  1. It is important to declare the prototype of all the user defined functions that will be defined in the same program.
  2. Function call – function is always called from the main function. It can be called multiple times as per requirement. When the function is called the program control goes to the function definition, which returns back to main as soon as all the statements in the function definition get executed.
  3. Function definition defines the functionality of function.

Passing Values between Functions:

The function described above is a simple function which is printing a simple message. Now, we will learn about some complex functions that takes input and returns some value as output.

The values that we send to the functions are called arguments or parameters.

For example, if I make a function that gives the sum of integers then it is obvious that this function needs the integers that should be given as inputs.

This code has a user defined function with the name “calsum”;

  • It calculates the sum of three numbers, sent as an argument.
  • It returns a single variable which is the sum of three numbers.
  • The numbers sent to the function must be of integer data type because it has been specified in the function definition and prototype.

It is clear from the this line of code “sum = calsum(a,b,c);” that the value returned from this function will be saved in the variable “sum”. This is how you can use the functions to assign values to any variable.