## Prevent Code Generation for Unused Execution Paths

If a variable controls the flow of an: `if, elseif, else` statement, or a ```switch, case, otherwise``` statement, declare it as constant so that code generation takes place for one branch of the statement only.

Depending on the nature of the control-flow variable, you can declare it as constant in two ways:

### Prevent Code Generation When Local Variable Controls Flow

1. Define a function `SquareOrCube` which takes an input variable, `in`, and squares or cubes its elements based on whether the choice variable, `ch`, is set to `s` or `c`:

```function out = SquareOrCube(ch,in) %#codegen if ch=='s' out = in.^2; elseif ch=='c' out = in.^3; else out = 0; end```
2. Generate code for `SquareOrCube` using the `codegen` command:

`codegen -config:lib SquareOrCube -args {'s',zeros(2,2)}`

The generated C code squares or cubes the elements of a 2-by-2 matrix based on the input for `ch`.

3. Add the following line to the definition of `SquareOrCube`:

`ch = 's';`

The generated C code squares the elements of a 2-by-2 matrix. The choice variable, `ch`, and the other branches of the `if/elseif/if` statement do not appear in the generated code.

### Prevent Code Generation When Input Variable Controls Flow

1. Define a function `MathFunc`, which performs different mathematical operations on an input, `in`, depending on the value of the input, `flag`:

```function out = MathFunc(flag,in) %#codegen %# codegen switch flag case 1 out=sin(in); case 2 out=cos(in); otherwise out=sqrt(in); end```
2. Generate code for `MathFunc` using the `codegen` command:

`codegen -config:lib MathFunc -args {1,zeros(2,2)}`

The generated C code performs different math operations on the elements of a 2-by-2 matrix based on the input for `flag`.

3. Generate code for `MathFunc`, declaring the argument, `flag`, as a constant using `coder.Constant`:

`codegen -config:lib MathFunc -args {coder.Constant(1),zeros(2,2)}`

The generated C code finds the sine of the elements of a 2-by-2 matrix. The variable, `flag`, and the `switch/case/otherwise` statement do not appear in the generated code.

## Support Get trial now