Page 78 - The Unofficial Guide to Lego Mindstorms Robots
P. 78

67


          Variables

          To use a variable, you simply need to declare its name. Only integer variables are supported. Once a variable is declared, you
          can assign the variable values and test it in the body of the program.
          Here's a simple example:

              int i;
            task main() {
                  i = 0;
                  while (i < 10) {
                      PlaySound (0);
                      Wait(5 ∗ i);
                      i += 1;
                  }
              }

          This example beeps at successively longer intervals. The varia ble, i, is declared in the very first line:

              int i;

          Values are assigned to the variable usin g the = operator:

              i = 0;

          You can also assign input values to vari ables, like this (not part of the example):

              i  = SENSOR_2;

          In the fo llowing line, one is added to the value in variable  :
                                                        i

              i++;

          This is really shorthand  for the following:

              i += 1;

          The += operator, in  turn, is shorthand for this:

              i = i + 1;

          Using #define for Constants an d Macros

          Constant values  can be assigned meaningf ul names using #define. This is a idiom that will be familiar to C programmers.
          He re is an example:

              #define POWER 5
              task main() {
              SetPower(OUT_A + OUT_C, POWER);
              On(OUT_A + OUT_C);
              }

          NQC replaces every occurrence of POWER with 5 in your source code before compiling it. Although this may not seem like a
          big deal, it is; #define lets you create
   73   74   75   76   77   78   79   80   81   82   83