Functions provide ways to break up code/common tasks into individual units. This helps to promote code re-usability and readability. When you find you are using the same code a lot of times it's most likely a good idea to put it in a function. This keeps files more compact and when corrections are needed a lot of time is saved and errors are prevented.


Declare functions with the keyword fun (or function) followed by the return type and then the name of the function. After the name of the function parentheses must be opened to declare the types of the input arguments.

// define function call ’funk’
fun void funk( int arg )
  // insert code here

The above function returns no values (the return type is void). If the function is declared to return any other type of values, the function body must return a value of the appropriate type.

// define function ’addOne’
fun int addOne(int x)
  // result
  return x + 1;

Note that the return keyword (without a argument) can be used in functions of type void as well, in which case it breaks off execution of the function and computation resumes from where the function was called. This is not unlike how the break keyword is used in loops and occasionally useful.

fun void noZero( int x)
  //stop at zero
  if ( x == 0 ) return;
  //otherwise print the input
  else <<< x >>>;


To call a function use the name of the function with appropriate arugments.

// define ’hey’
fun int hey( int a, int b )
  // do something
  return a + b;
// call the function; store result
hey( 1, 2 ) => int result;

You can also use the ChucK operator to call functions!

// call hey
( 1, 2 ) => hey => int result;

// same
hey( 1, 2 ) => int result;

// several in a row
( 10, 100 ) => Std.rand2 => Std.mtof => float foo;

// same
Std.mtof( Std.rand2( 10, 100 ) ) => float foo;


Overloading a function allows functions with the same name to be defined with different arguments. The function must be written in separate instances to handle the input, and the return type must be the same for all versions.

// funk( int )
fun int add(int x)
  return x + x;

// funk( int, int )
fun int add(int x, int y)
  return x + y;

// compiler automatically choose the right one to call
add( 1 ) => int foo;
add( 1, 2 ) => int bar;

In some cases multiple versions of the function may apply, most notably when type bar extends type foo and our fuction is overloaded to handle both. In that case ChucK should prefer the most speciffic one over the more general case.