C Language | Functions | Parameters and Return Values

Functions can receive values to use in their processing and return results to the caller.

Passing Values to a Function

The information passed to a function is called an argument. A variable declared by the function to receive an argument is called a parameter. Specify each parameter’s type and identifier inside the parentheses of the function definition. Separate multiple parameters with commas.

void Function(int iValue, float fValue) { ...

When calling the function, pass expressions that are compatible with the parameter types.

Code 1

#include <stdio.h>

void Function(int iValue, float fValue) {
  printf("iValue = %d : fValue = %g\n", iValue, fValue);
}

int main() {
  Function(10, 3.14F);
  Function(100, 1000);
  return 0;
}

In Function(100, 1000), an int argument is passed to a float parameter. As with assignment, an implicit conversion is applied when the types are compatible. Parameters such as iValue and fValue can be used only inside the function where they are declared.

Returning a Result

A function can return a value to its caller. The caller may store that value or ignore it.

Code 2

#include <stdio.h>

int Triangle(int iBase, int iHeight) {
  return iBase * iHeight / 2;
}

int main() {
  int iBase, iHeight, iArea;
  printf("Enter the base and height of the triangle. >");
  scanf("%d %d", &iBase, &iHeight);

  iArea = Triangle(iBase, iHeight);
  printf("Triangle area = %d\n", iArea);
  return 0;
}

Triangle() receives a base and height and returns the area. Variables with the same identifiers may be declared in different functions because each function has its own scope.

Older C permitted an omitted return type and treated it as int. This legacy syntax is not supported by modern C standards and causes an error in C++. Always write the return type explicitly in new code.

Code 3

#include <stdio.h>

int Function(void) {
  printf("Function()\n");
  return 0;
}

int main(void) {
  return Function();
}

Explicit types make the function’s purpose clear and avoid relying on obsolete syntax.