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

76


          Table 4-7. Argument Passing for Inlines

          Type            By Value or By Reference?      Temporary Variable Used?

          i nt      by    value                     yes

          c onst int   by  value                    no

          int&       by   reference                 no

          co nst int&  by  re ference               no

          If you pass int by value,  the parameter's value is copied into a temporary variable (from the pool of 31) and used in the
          inline. const int passes by  value, but the value must be a constant at compile time.

          If you pass by reference, the variable that is passed in can actually be modified in the inline. In this code, for example, a
          count variable is incremented in the body of an inline:

              task main() {
                  int count = 0;
                  while (count <= 5) {
                      PlaySound(SOUND_CLI    CK);
                      Wait(count ∗ 20);
                      increment(count);
                  }
              }
              void increment(int& n) {
                  n++;
              }

          Th e last option, const int &, is u sed when you want to pass a value that should not be changed. This is great for things
          like Sensor() and Timer().  For e xample, you might have an inline like this:

              void forward(const int& power) {
                  SetPower(OUT_A + OUT_C, power);
                  OnFwd(OUT_A + OUT_C);
              }

          With this inline, you can  do normal things, like passing  a variable or constant:

              int power = 6;
              for war d(power);

              forward(OUT_HALF);

          But you can also do trickier stuff, like this:

              forward(Message());

          You can basically accomplish the same stuff with int parameters and const int& parameters. The advantage of const
          int& is that no temporary variables are used.
   82   83   84   85   86   87   88   89   90   91   92