Main Content

coder.mustBeConst

Validate that value is a compile-time constant

Since R2023b

Description

coder.mustBeConst(value) validates that the function input value is a constant during code generation, also referred to as a compile-time constant in this context. During code generation, this function throws an error if value is not a compile-time constant. During MATLAB® execution, this function has no effect.

example

Examples

collapse all

This example shows how to validate that an input to a function that is called from the entry-point function is a constant during code generation, also referred to as a compile-time constant.

Define an entry-point function testConstant that calls a local function local. The first input to the local function is validated to be a compile-time constant using the coder.mustBeConst validator.

function out = testConst(in1,in2)
if in1 > 0
    out = local(in1,in2);
else
    out = local(-in1,in2);
end
end

function u = local(x,y)
arguments
    x {coder.mustBeConst}
    y 
end
u = sqrt(x) + y;
end

Generate code for the testConst function using the codegen command. Specify the entry-point inputs in1 and in2 to be scalar doubles using the -args option.

codegen testConst -args {0,0}
Value must be constant.

Error in ==> testConst Line: 11 Column: 8
Code generation failed: View Error Report

Code generation fails because the absolute value of the run-time input in1 is directly passed as the first argument when calling the function local. Because this value is not known at compile time, the coder.mustBeConst validator throws an error during code generation.

Modify the codegen command by specifying the first entry-point input to be of a constant type using the coder.Constant function.

codegen testConst -args {coder.Constant(0),0}
Code generation successful.

Because the first input passed to local is of a constant type, the coder.mustBeConst validator does not throw an error and code generation succeeds.

Input Arguments

collapse all

Value to validate as a compile-time constant, specified as a scalar or array of one of the data types listed below. This argument can also be an instance of a value class that you authored. Passing handle objects to coder.mustBeConst is not supported.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string | struct | cell | function_handle | categorical | datetime | duration | fi

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Version History

Introduced in R2023b

See Also