Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime conditional typedef in C

Tags:

c

types

typedef

I know there is a C++ version of this question, however I'm using standard typedefs not templates.

I've written a program that works with 16-bit wav files. It does this by loading each sample into a short. The program then performs arithmetic on the short.

I'm now modifying the program so it can with with both 16- and 32-bit wavs. I was hoping to do a conditional typedef, i.e. using short for 16-bit and int for 32-bit. But then I realised that the compiler probably would not compile the code if it did not know what the type of a variable is beforehand.

So I tried to test out the following code:

#include <stdio.h>

int
main()
{
  int i;
  scanf("%i", &i);

  typedef short test;

  if(i == 1)
    typedef short sample;
  else 
    typedef int sample;

  return 0;
}

And got got the following compiler errors:

dt.c: In function ‘main’:
dt.c:12:5: error: expected expression before ‘typedef’
dt.c:14:5: error: expected expression before ‘typedef’

Does this mean that runtime conditional typedefs in C are not possible?

[Open-ended question:] If not, how would you guys handle something like this?

like image 713
rhlee Avatar asked Mar 05 '26 14:03

rhlee


2 Answers

typedef is a compiler feature, you cannot apply it on runtime.

like image 104
MByD Avatar answered Mar 07 '26 09:03

MByD


All types in a program must be known at compile time.

In C++ you could compile your code for short and int using templates; in C you can do this using macros (specifically, X-macros).

Put your calculation code in a separate file called e.g. dt.tmpl.c, then in dt.c write:

#define sample int
#include "dt.tmpl.c"

#define sample short
#include "dt.tmpl.c"

Your dt.tmpl.c code can then use sample as a preprocessor token to name types and paste into function names, for example:

#define PASTE(name, type) name ## _ ## type
#define FUNCTION_NAME(name, type) PASTE(name, type)

sample FUNCTION_NAME(my_calculation, sample)(sample i) {
    return i * 2;
}

This will result in two functions int my_calculation_int(int i) and short my_calculation_short(short i) which you can then use elsewhere.

like image 37
ecatmur Avatar answered Mar 07 '26 11:03

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!