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 the coder.nullcopy function, as described in How to Eliminate Redundant Copies by Defining Uninitialized Variables.

How to Eliminate Redundant Copies by Defining Uninitialized Variables

  1. Define the variable with coder.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 statement X = zeros(1,N) not only defines X to be a 1-by-5 vector of real doubles, but also initializes each element of X to zero.

function X = withoutNullcopy %#codegen

N = 5;
X = zeros(1,N);
for i = 1:N
    if mod(i,2) == 0
        X(i) = i;
    elseif mod(i,2) == 1
        X(i) = 0;
    end
end

This forced initialization creates an extra copy in the generated code. To eliminate this overhead, use coder.nullcopy in the definition of X:

function X = withNullcopy %#codegen

N = 5;
X = coder.nullcopy(zeros(1,N));
for i = 1:N
    if mod(i,2) == 0
        X(i) = i;
    else
        X(i) = 0;
    end
end

See Also

Related Topics