Code Generation for Enumerations

Enumerations represent a fixed set of named values. Enumerations help make your MATLAB® code and generated C/C++ code more readable. For example, the generated code can test equality with code such as if (x == Red) instead of using strcmp.

For code generation, when you use enumerations, adhere to these restrictions:

Define Enumerations for Code Generation

For code generation, the enumeration class must derive from one of these base types: int8, uint8, int16, uint16, or int32. For example:

classdef PrimaryColors < int32
    enumeration
        Red(1),
        Blue(2),
        Yellow(4)
    end
end

You can use the base type to control the size of an enumerated type in generated C/C++ code. You can:

  • Represent an enumerated type as a fixed-size integer that is portable to different targets.

  • Reduce memory usage.

  • Interface with legacy code.

  • Match company standards.

The base type determines the representation of the enumerated type in generated C/C++ code.

If the base type is int32, the code generator produces a C enumerated type. Consider the following MATLAB enumerated type definition:

classdef LEDcolor < int32
    enumeration
        GREEN(1),
        RED(2)
    end
end

This enumerated type definition results in the following C code:

enum LEDcolor
{
    GREEN = 1,
    RED
};

typedef enum LEDcolor LEDcolor;

For built-in integer base types other than int32, the code generator produces a typedef statement for the enumerated type and #define statements for the enumerated values. Consider the following MATLAB enumerated type definition:

classdef LEDcolor < int16
    enumeration
        GREEN(1),
        RED(2)
    end
    
end
This enumerated type definition results in the following C code:
typedef short LEDcolor;
#define GREEN ((LEDcolor)1)
#define RED ((LEDcolor)2)

The C type in the typedef statement depends on:

Use Allowed Operations on Enumerations

For code generation, you are restricted to the operations on enumerations listed in this table.

OperationExample

assignment operator, =

xon = LEDcolor.GREEN
xoff = LEDcolor.RED

relational operators,< > <= >= == ~=

You cannot use == or ~= to test equality between an enumeration member and a character array or cell array of character arrays.

xon == xoff

cast operation

double(LEDcolor.RED)

indexing operation

m = [1 2]
n = LEDcolor(m)
p = n(LEDcolor.GREEN)

control flow statements: if, switch, while

if state == sysMode.ON
    led = LEDcolor.GREEN;
else
    led = LEDcolor.RED;
end

Use MATLAB Toolbox Functions That Support Enumerations

For code generation, you can use enumerations with these MATLAB toolbox functions:

More About

Was this topic helpful?