Function declaration (ZScript)

From ZCWiki
Jump to: navigation, search

Function declarations define the return type and arguments for a function.

Syntax

The syntax for a function declaration is as follows:

return-type function-name(function-parameters){
  // Function contents go here.

  // If the function returns a value, the function
  // must contain at least one return statement.
  return return-value;
}

return-type must either be one of the valid data types (such as int or bool) if the function is to return a value, or void if the function will not return anything.

function-name is the user-defined name of the function. This is the name you use to run ("call") the function from another function.

function-parameters is the list of values that will be provided to the function. A data type is specified for each value, and multiple values are separated by commas. function-parameters is not required; some functions may not use any input values.

The run() function has a few special rules.

Examples

This first example is a simple function that returns the cube of a number. The name of the function is "Cube", it takes one integer value "NumberToCube" as an input, and it returns an integer value that is the cube of "NumberToCube".

// This function returns the cube of a number, as an integer value.
// It takes one intput, the number to be cubed.
int Cube(int NumberToCube){
  return NumberToCube * NumberToCube * NumberToCube;
}

The next example, function "Largest", uses two integers as inputs. It returns the largest of the two integers.

// This function returns the largest of two integers.  In this function,
// a local variable is declared to store the largest value.
int Largest(int X, int Y){
  // Local declarations.
  int LargestNum;

  if(X > Y){
    LargestNum = X;
  }
  else {
    LargestNum = Y;
  }

  return LargestNum; 
}

This last example doesn't return any values (thus it does not include a return statement), nor does it take any input parameters.

// Kill Link!
void KillLink(){
  Link->HP = 0;
}

See Also