Functions

Functions

C uses the function to “"”package””” blocks of code.

return-type function-name(argument1, argument2, ..,argumentN) {
	/* code */
	return <value>;
}

A function has a name, arguments, and the code associate with it. There is a special function called main that indicates where the program begins.

/*
* Computes double of a number.
* works by tripling the number, then subtracting to get back to duble.
*/

static int Twice(int num) {
	int result = num * 3;
    	result = result - num;
	return result;
}

The static keyword makes it so that the function will be only avaliable to callers in the file where it is declared. If it needs to be used across files then it will need a prototype/be defined in a header file

Paramaters in functions are passed by value. The paramater is evaluated in the callers context. The alternative “by reference” must be manually implemented. When a parameter is a structure, it is copied.

The caller and callee functions do not share any memory. So modifications are not commited back to the caller. To overide this you need to pass by reference

To pass an ovject X as a reference paramter, the programmer must pass a pointer to X instead of X itself.

Example of by refernce

static void Swap(int* x, int* y) {
  int temp;

  temp = *x;
  *x = *y;
  *y = temp;
}

Another example of changing something by reference

#include <stdio.h>

void foo(int* ptr);

int main(void)
{
    int x =4;
    int* ptr = &x;
    printf("%d\n", *ptr);
    foo(ptr);
    printf("%d\n", *ptr);
}

void foo(int* ptr) {
    *ptr = 3;
}