C choosing variable type at run-time

Viewed 71

I have this piece of code below which seems very explicit and redundant, is there a way to choose variable type at run-time?

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);
    }
}

I'm looking for something like this:

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 Answers

C's only tool for writing generic code is with macros, but that's not necessary here.

Skip the formality of declaring a variable of precisely the right type and instead just read or write the appropriate number of bytes:

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);
}

Since your code doesn't really care what the values are, just how many bytes they require, you can just use character buffers.

You cannot do this, I suggest you to use the same variable type, for example you can cast a int to char and you will reach the correct value

Related