C在运行时选择变量类型

时间:2018-11-15 16:22:33

标签: c syntactic-sugar

我下面的这段代码看起来非常明确和多余,有没有办法在运行时选择变量类型?

if(header->bitsPerSample == 16) {
    int sample;
    for (int i = 0; i < header->chunkSize - HEADER_SIZE + 8; i += sizeof(sample) * 2) {
        fread(&sample, sizeof(sample), 1, fp);
        fwrite(&sample, sizeof(sample), 1, new);
        fread(&sample, sizeof(sample), 1, fp);
    }
} else if(header->bitsPerSample == 8) {
    char sample;
    for (int i = 0; i < header->chunkSize - HEADER_SIZE + 8; i += sizeof(sample) * 2) {
        fread(&sample, sizeof(sample), 1, fp);
        fwrite(&sample, sizeof(sample), 1, new);
        fread(&sample, sizeof(sample), 1, fp);
    }
}

我正在寻找这样的东西:

if(header->bitsPerSample == 16) 
    sample is of type int
else if(header->bitsPerSample == 8)
    sample is of type char

for (int i = 0; i < header->chunkSize - HEADER_SIZE + 8; i += sizeof(sample) * 2) {
        fread(&sample, sizeof(sample), 1, fp);
        fwrite(&sample, sizeof(sample), 1, new);
        fread(&sample, sizeof(sample), 1, fp);
}

2 个答案:

答案 0 :(得分:6)

C编写通用代码的唯一工具是宏,但这不是必需的。

跳过声明恰好正确类型的变量的形式,而只需读取或写入适当数量的字节即可:

size_t raw_size = header->bitsPerSample / 8;
unsigned char buffer[raw_size];
void* raw = &buffer;

for (int i = 0; i < header->chunkSize - HEADER_SIZE + 8; i += raw_size * 2) {
  fread(raw, raw_size, 1, fp);
  fwrite(raw, raw_size, 1, new);
  fread(raw, raw_size, 1, fp);
}

由于您的代码实际上并不关心值是多少,因此它们只需要多少字节,因此您可以使用字符缓冲区。

答案 1 :(得分:2)

您不能执行此操作,建议您使用相同的变量类型,例如,可以将int强制转换为char并达到正确的值