C Function Parameters

Functions become far more useful when you can pass information into them. These pieces of information are called parameters. A parameter lets the same function work with different data each time you call it, so one greet() can welcome many different people.

Passing Data Into a Function

You declare parameters inside the parentheses of a function, each with a type and a name. When you call the function you provide matching values, which are called arguments. The parameter acts like a variable that receives the argument's value.

A function with one parameter

#include <stdio.h>

void greet(char name[]) {
  printf("Hello, %s!\n", name);
}

int main() {
  greet("Aisha");
  greet("Bruno");
  return 0;
}
Note: The words 'parameter' and 'argument' are often mixed up. A parameter is the name listed in the function definition. An argument is the actual value you pass when calling. In greet("Aisha"), name is the parameter and "Aisha" is the argument.

Multiple Parameters

A function can take as many parameters as you need. Separate them with commas, and give each one its own type. When you call the function, pass the arguments in the same order the parameters are listed.

Adding two numbers with parameters

#include <stdio.h>

int add(int a, int b) {
  return a + b;
}

int main() {
  int sum = add(8, 12);
  printf("8 + 12 = %d\n", sum);
  return 0;
}

Order Matters

C matches arguments to parameters by position, not by name. The first argument fills the first parameter, the second fills the second, and so on. If you swap the order, you may get a different result, so always double-check the sequence.

Position decides the result

#include <stdio.h>

void describe(char name[], int age) {
  printf("%s is %d years old.\n", name, age);
}

int main() {
  describe("Maya", 30);
  return 0;
}

Pass By Value

  • C passes a copy of the argument into the parameter
  • Changing the parameter inside the function does not change the original variable outside
  • This behaviour is called 'pass by value' and is the default in C
  • To let a function change the caller's variable you would use pointers, covered later

Parameter quick reference

TermWhere it appearsExample
ParameterIn the function definitionint add(int a, int b)
ArgumentIn the function calladd(8, 12)
Return valueSent back with returnreturn a + b;