← Back to C Course | Chapter 7: Pointers | Lesson 5 of 9

C Pointers & Functions

Call by Value

This is C's default parameter-passing behavior for all non-array, non-pointer types -- it protects the caller's data but means the function has no way to report a result back except through its return value, which limits it to a single output.

Example: Call by Value

c
#include <stdio.h>
void tryChange(int x) {
	x = 100;
}
int main() {
	int value = 5;
	tryChange(value);
	printf("%d", value);
	return 0;
}

Call by Reference

This is the standard technique C uses to simulate 'output parameters,' since a function can only truly return one value -- functions like scanf() rely entirely on this pattern, which is why you write scanf("%d", &x) with the address-of operator.

Example: Call by Reference

c
#include <stdio.h>
void change(int *x) {
	*x = 100;
}
int main() {
	int value = 5;
	change(&value);
	printf("%d", value);
	return 0;
}

Swapping Two Numbers

A classic teaching example that demonstrates why call by value alone can't swap two variables: the function must receive pointers to both variables so it can dereference and exchange their actual stored values, not just local copies.

Example: Swapping Two Numbers

c
#include <stdio.h>
void swap(int *a, int *b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}
int main() {
	int x = 5, y = 10;
	swap(&x, &y);
	printf("%d %d", x, y);
	return 0;
}

Returning Pointers from Functions

This is a genuinely dangerous pattern to avoid -- a local variable's memory is reused as soon as the function returns, so a pointer to it becomes a 'dangling pointer' pointing at invalid, potentially overwritten memory.

Example: Returning Pointers from Functions

c
#include <stdio.h>
int* getStatic() {
	static int value = 42;
	return &value;
}
int main() {
	int *ptr = getStatic();
	printf("%d", *ptr);
	return 0;
}

Passing Pointer Arrays

Passing an array of pointers (like char *names[]) lets a single function operate on a whole collection of separately-allocated strings or structures without needing to know their individual sizes in advance -- this is exactly how argv works in main().

Example: Passing Pointer Arrays

c
#include <stdio.h>
void printNames(char *names[], int count) {
	for (int i = 0; i < count; i++) {
		printf("%s ", names[i]);
	}
}
int main() {
	char *names[2] = {"Ann", "Bob"};
	printNames(names, 2);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.