user2682877
user2682877

Reputation: 550

passing a type as a parameter in C

I'm writting a function where I have the parameter "size", and depending of the value of size, I would use the type unsigned char, unsigned short or unsigned int. Typically, I'm trying to do something like that :

if (size == 1) {unsigned char * memory = calloc(sizeOfFile,1);}
if (size == 2) {unsigned short * memory = calloc(sizeOfFile,1);}
if (size == 4) {unsigned int * memory = calloc(sizeOfFile,1);}

where i could use "memory" outside of the "if". Is there any way to do that or do I have to copy my function 3 times into each "if" ?

Thanks in advance.

Upvotes: 2

Views: 533

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

There is no way of passing a type to a C function, because a type is a compile-time concept. Once the compiler is finished, there's no type to talk about: the knowledge of the types is "baked into" the binary code the compiler generates, with no additional metadata to make available to your program.

Instead of passing a type, you can pass a size, and do pointer math by yourself. Take qsort or bsearch functions as an example: they both work on untyped arrays as if they knew the exact type. The "magic" that lets these functions do it is in the size_t nel parameter, and a function pointer taking const void * arguments.

You can model your API in the same way. You are taking the size as a parameter already, so what's remains is the pointer math. Convert the pointer to char * so that adding size would advance the pointer to the next element of the "type", perform the arithmetics to advance the pointer to your target, and then convert the pointer back to void*.

Upvotes: 5

Paul R
Paul R

Reputation: 212979

If it's a relatively small function you can write a macro:

#define FOO(T, x, y, z) do \
{ \
    T * memory = calloc(sizeOfFile, 1); \
    ... \
    ... \
    ... \
} while(0)

which you would then call as, e.g.

FOO(char, x, y, z);

or

FOO(int, x, y, z);

It's ugly, and the usual caveats about macros apply, but in some cases it might be a reasonable solution.

Upvotes: 2

unwind
unwind

Reputation: 399861

It depends on what you want to do.

Your allocations all allocate a sizeofFile bytes, which is probably not what you want to be doing.

You could use a void * pointer, but that will require that you check the type when accessing later of course.

It would be easier to help you if your question was more concrete, I think.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224964

Normally you'd just use a void * pointer and keep track of the type in a separate variable.

Upvotes: 1

Related Questions