NXC  Version 1.2.1 r5
 All Data Structures Files Functions Variables Groups Pages
Code Order

Code order has two aspects: the order in which the code appears in the source code file and the order in which it is executed at runtime.

The first will be referred to as the lexical order and the second as the runtime order.

The lexical order is important to the NXC compiler, but not to the NXT brick. This means that the order in which you write your task and function definitions has no effect on the runtime order. The rules controlling runtime order are:

  1. There must be a task called main and this task will always run first.
  2. The time at which any other task will run is determined by the API functions documented in Command module functions section.
  3. A function will run whenever it is called from another block of code.

This last rule may seem trivial, but it has important consequences when multiple tasks are running. If a task calls a function that is already in the midst of running because it was called first by another task, unpredictable behavior and results may ensue. Tasks can share functions by treating them as shared resources and using mutexes to prevent one task from calling the function while another task is using it. The The safecall keyword keyword (see Functions) may be used to simplify the coding.

The rules for lexical ordering are:

  1. Any identifier naming a task or function must be known to the compiler before it is used in a code block.
  2. A task or function definition makes its naming identifier known to the compiler.
  3. A task or function declaration also makes a naming identifier known to the compiler.
  4. Once a task or function is defined it cannot be redefined or declared.
  5. Once a task or function is declared it cannot be redeclared.

Sometimes you will run into situations where is impossible or inconvenient to order the task and function definitions so the compiler knows every task or function name before it sees that name used in a code block. You can work around this by inserting task or function declarations of the form

task name();
return_type name(argument_list);

before the code block where the first usage occurs. The argument_list must match the list of formal arguments given later in the function's actual definition.