有没有办法摆脱这个开关,把它变成一个更小的代码块?

Is there a way to get rid of this switch and make it into a smaller block of code?

我的代码中有这个开关,它占用了大量 space。有没有办法让它变成更小的代码块?

switch(datatype)
{
    case OSMP_BYTE: // char
    {
        datatypeSize = sizeof(char);
        break;
    }
    case OSMP_INT: // int
    {
        datatypeSize = sizeof(int);
        break;
    }
    case OSMP_SHORT: // short int
    {
        datatypeSize = sizeof(short int);
        break;
    }
    case OSMP_LONG: // long int
    {
        datatypeSize = sizeof(long int);
        break;
    }
    case OSMP_UNSIGNED_CHAR: // unsigned char
    {
        datatypeSize = sizeof(unsigned char);
        break;
    }
    case OSMP_UNSIGNED: // unsigned int
    {
        datatypeSize = sizeof(unsigned int);
        break;
    }
    case OSMP_UNSIGNED_LONG: // unsigned long int
    {
        datatypeSize = sizeof(unsigned long int);
        break;
    }
    case OSMP_FLOAT: // float
    {
        datatypeSize = sizeof(float);
        break;
    }
    case OSMP_DOUBLE: // double
    {
        datatypeSize = sizeof(double);
        break;
    }

    default:
        break;
}

我的数据类型定义如下:

typedef enum {
    OSMP_SHORT = 1,
    OSMP_INT,
    OSMP_LONG,
    OSMP_UNSIGNED_CHAR,
    OSMP_UNSIGNED,
    OSMP_UNSIGNED_LONG,
    OSMP_FLOAT,
    OSMP_DOUBLE,
    OSMP_BYTE
} OSMP_Datatype;

如果有办法让它更小并且更适合我的代码,我真的会得到帮助。

这是一种可能的查找方法table,正如评论中所建议的那样:

typedef enum {
    OSMP_SHORT = 0,
    OSMP_INT,
    OSMP_LONG,
    OSMP_UNSIGNED_CHAR,
    OSMP_UNSIGNED,
    OSMP_UNSIGNED_LONG,
    OSMP_FLOAT,
    OSMP_DOUBLE,
    OSMP_BYTE,
} OSMP_Datatype;

size_t OSMP_Size[] = 
{
    [OSMP_SHORT] = sizeof(short int),
    [OSMP_INT] = sizeof(int),
    [OSMP_LONG] = sizeof(long int),
    [OSMP_UNSIGNED_CHAR] = sizeof(unsigned char),
    [OSMP_UNSIGNED] =  sizeof(unsigned int),
    [OSMP_UNSIGNED_LONG] = sizeof(unsigned long int),
    [OSMP_FLOAT] = sizeof(float),
    [OSMP_DOUBLE] = sizeof(double),
    [OSMP_BYTE] = sizeof(char),
};

size_t sizeofType(OSMP_Datatype type)
{
    if((type >= 0) && (type < sizeof(OSMP_Size)/sizeof(size_t)))
        return OSMP_Size[type];
    else
        return 0;
}

这里最好枚举是连续的并且从零开始,因为这样查找更容易实现。请注意,这使用指定的初始值设定项,因此它仅适用于 C99 向上。正如@paddy 所指出的,也与 C++ 不兼容。

此外,代码可能看起来更紧凑,但不要期望它比您的 switch-case 执行得更好。

My datatypes are defined like this:

为了好玩,试试:

typedef enum {
    OSMP_SHORT = (0 << 16) | sizeof(short),
    OSMP_INT = (1 << 16) | sizeof(int),
    OSMP_LONG = (2 << 16) | sizeof(long),
    OSMP_UNSIGNED_CHAR = (3 << 16) | sizeof(unsigned char),
    OSMP_UNSIGNED = (4 << 16) | sizeof(unsigned),
    OSMP_UNSIGNED_LONG = (5 << 16) | sizeof(unsigned long),
    OSMP_FLOAT = (6 << 16) | sizeof(float),
    OSMP_DOUBLE = (7 << 16) | sizeof(double),
    OSMP_BYTE = (8 << 16) | sizeof(uint8_t),
} OSMP_Datatype;

#define OSMP_DataSizeMask 0x0000FFFF

..然后代码可以是:

    datatypeSize = datatype & OSMP_DataSizeMask;