c functions

c functions are not mathematical functions

  • mathematical functions can not modify their context/environment
  • the term "routine" may be technically more appropriate

caller and callee

the caller is the function that makes a call to another function. the other called function is the callee

call by value

  • call by value means that function arguments are copied to be used by the callee
  • this ensures that changing the arguments in the caller scope is not possible in the callee
  • no thought has to be given to the questions of if parallel code might change the argument values while they are being used

call by contract

  • call by contract is a design pattern that requires the user to ensure that the function will support the arguments when called
  • in other words, it is the responsibility of the caller to ensure that the arguments match the functions domain
  • functions need to abstract less and execute only the minimum
  • with call by contract, functions do not check for or reject invalid data that might have been passed


  • functions can return one value
  • functions can modify data via pointer arguments
  • the single return value can be used to return an error identifier after writing result values via pointer arguments

    • there is always only one error status but multiple result values are possible

argument order

for example, acted-on arguments first, and output arguments last:

  • string_append :: a b result
  • list_add :: list value

especially when the argument count is variable, it may be preferable to put the output arguments first:

  • generate_2d :: out x y
  • generate_3d :: out x y z

local versus global variables

using globals might save declaration overhead, but access of a local is often faster because the compiler can better predict where it will be modified and prepare to cache data

performance example

  • global

    • 0m10.745s
    • 0m10.739s
  • local

    • 0m9.931s

    • 0m9.940s

content structure

all stack allocations are made at the beginning of a function call, regardless of where they are declared. having all declarations grouped together at the beginning of functions may make it clearer what is actually happening. having all declarations at the top may make finding declarations easier than searching them scattered throughout the function body.

patterns of function usage

  • allocates and returns memory

    • can return null for failure or an address otherwise
    • need to return size if size is determined in function
    • con: can not use stack allocated memory, can not use custom allocator
  • receives and uses memory for input or output
  • allocates and frees memory
  • has output arguments
  • has only the return argument
  • can fail and return error code or uses only non-failing features
  • modifies input