Main Content

Eliminate Redundant Copies of Variables in Generated Code

When Redundant Copies Occur

During C/C++ code generation, the code generator checks for statements that attempt to access uninitialized memory. If it detects execution paths where a variable is used but is potentially not defined, it generates a compile-time error. To prevent these errors, define variables by assignment before using them in operations or returning them as function outputs.

Note, however, that variable assignments not only copy the properties of the assigned data to the new variable, but also initialize the new variable to the assigned value. This forced initialization sometimes results in redundant copies in C/C++ code. To eliminate redundant copies, define uninitialized variables by using thecoder.nullcopyfunction, as described inHow to Eliminate Redundant Copies by Defining Uninitialized Variables.

How to Eliminate Redundant Copies by Defining Uninitialized Variables

  1. Define the variable withcoder.nullcopy.

  2. Initialize the variable before reading it.

    When the uninitialized variable is an array, you must initialize all of its elements before passing the array as an input to a function or operator — even if the function or operator does not read from the uninitialized portion of the array.

    What happens if you access uninitialized data?

Defining Uninitialized Variables

In the following code, the assignment statementX = zeros(1,N)not only definesX1-by-5向量的双打,但也在itializes each element ofXto zero.

functionX = withoutNullcopy%#codegenN = 5; X = zeros(1,N);fori = 1:Nifmod(i,2) == 0 X(i) = i;elseifmod(i,2) == 1 X(i) = 0;endend

This forced initialization creates an extra copy in the generated code. To eliminate this overhead, usecoder.nullcopyin the definition ofX:

functionX = withNullcopy%#codegenN = 5; X = coder.nullcopy(zeros(1,N));fori = 1:Nifmod(i,2) == 0 X(i) = i;elseX(i) = 0;endend

See Also

Related Topics