2020-11-09

c functions

c functions arent mathematical functions

  • mathematical functions cant change their environment
  • the term "routine" might 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 is when arguments are copied to be used by the callee
  • this ensures that changing the arguments in the caller scope is not possible
  • 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 the user to ensure that the function supports the arguments, that they are part of the functions domain
  • it allows functions to abstract and execute only the minimum
  • with call by contract, functions dont check for or reject invalid data that might have been passed

output

  • 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 calculated result values to data via arguments

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

argument order

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

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

especially when the argument count can vary, it might make sense to put the output arguments first and others last

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

local vs global variables

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

performance example

  • global

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

    • 0m9.931s

    • 0m9.940s

structure

all stack allocations are being made at the beginning of a function anyway, regardless of where they are made, and having all declarations at the beginning groups this type of preparation, so it might make sense to have all declarations at the top. it's tedious to declare all variables before they are being used, but having it at the top might make it easier to find than scattered through the function

function pattern

  • allocates and returns memory

    • can return null for failure or address otherwise
    • need to return size if size is determined in function
    • con: cant use stack allocated memory, cant 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 basic features
  • modifies input