How to create and call a function with parameter in C

About C function with parameter

In C programming, a function can be declared with parameters. Parameters are used to pass data inside the function.

A function may have single or multiple parameters of different data types though it can be declared without parameter.

Parametrs are placed inside the parentheses '()' of the function. Each parameters are seperated by comma (,).

Data type of parameter must be declared at the time of function declaration and definition.

Please note that the data types of the arguments passed to a function must match the data types of the parameters specified in the function declaration and definition.

Create and call a function with parameters

A function with parameters will be created and called in the following examples:

Example of defining a function with parameter

Explanation of code:

  • int addNumber(int a, int b): The line defines a function named 'addNumber' with two integer parameters 'int a' and 'int b'. int is the data type of parameters and a and b are names of parameters.
  • return a + b;: The function operates on the parameters by adding their values. This returns the sum of values of two parameters 'a' and 'b'. The result will be of an integer type.
Example of calling a function with parameters
Output of the above example
11

Explanation of code:

  • int sum = addNumber(7, 4);: The code 'addNumber(7, 4)' calls the 'addNumber' function passing two integer arguments 7 and 4 that match the data types of parameters. The returned result is assigned to an integer variable 'sum'. Please note that two integer numbers are passed as function arguments.
  • printf("%d", sum);: The line prints the value of 'sum' variable. The '%d' is the format specifier for integer data in C program.
Example of calling a function passing variables as arguments
Output of the above example
The sum is 25

Explanation of code:

  • int sum = addNumber(num1, num2);: The code 'addNumber(num1, num2)' calls the 'addNumber' function passing two integer variables 'num1' and 'num2' that match the data types of parameters. The return result is assigned to an integer variable 'sum'. Please note that two integer variables are passed as function arguments.
  • printf("The sum is %d", sum);: The line prints the value of 'sum' variable.

Live Code Playground

In the following C code editor, you can practice by creating more C functions with parameters of different data types. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output