Enumerated Types Supported for Code Generation

An enumerated type is a user-defined type whose values belong to a predefined set of enumerated values. Each enumerated value consists of a name and an underlying numeric value.

You define an enumerated data type in an enumeration class definition file. For code generation, you must base the class on int8, uint8, int16, uint16, or int32. For example:

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

In this example, the statement classdef(Enumeration) PrimaryColors < int32 means that the enumerated type PrimaryColors is based on the built-in type int32. PrimaryColors inherits the characteristics of the int32 type. It also defines its own unique characteristics. For example, PrimaryColors is restricted to three enumerated values:

Enumerated ValueEnumerated NameUnderlying Numeric Value
Red(1)Red1
Blue(2)Blue2
Yellow(4)Yellow4

Enumeration Class Base Types for Code Generation

For code generation, you must base an enumerated type on one of the following built-in MATLAB® integer data types:

  • int8

  • uint8

  • int16

  • uint16

  • int32

If you use MATLAB Coder™ to generate C/C++ code , you can use the base type to control the size of an enumerated type in the generated code. You can:

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

  • Reduce memory usage.

  • Interface to legacy code.

  • Match company standards.

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

C Code Representation for Base Type int32

If the base type is int32, the code generation software generates a C enumeration type. Consider the following MATLAB enumerated type definition:

classdef(Enumeration) 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;

C Code Representation for Base Type Other Than int32

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

classdef(Enumeration) 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:

Was this topic helpful?