Aussie AI

Use Parameters as local variables

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Use Parameters as local variables

Parameters to functions can be used as if they were local variables. Because of C++ call-by-value parameter passing of basic data types (not arrays), the modification of a parameter inside the function does not change the values of any variables not local to the function. This method saves on initialization time, and on stack space. In the example below, to zero an array, the size is counted down, rather than having a local variable counting up.

    void zero_array(int arr[], int n)
    {
        while (n > 0)
            arr[--n] = 0;
    }

This code also has the optimization of “looping down to zero”. Note that we have to be careful that this code doesn't access arr[n], but does correctly clear arr[0]. I think it works correctly, but my brain is on fire trying to check it.

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++