1

I am trying to map a number to a keyword type in C. Is there anyway to do this?

#include <stdio.h>
#include <stdlib.h>
#include "memory.h"

#define DOUBLE_TYPE 1
#define INT_TYPE 2

#define OBJECT_TYPE(Y)
        #if Y == DOUBLE_TYPE \
                double \
        #elif Y == INT_TYPE \
                int \
        #else \
                int \
        #endif \

int main(int argc, char* argv[]) {
        unsigned int type = 1;
        OBJECT_TYPE(type) value = 0.5f;
        printf("%f\n", value);

        return 0;
}
test.c:11:3: error: missing binary operator before token "double"
   double \

I want to be able to cast a void* to a specific type known by the integer code.

5
  • The C preprocessor has no concept of data types. You cannot nest directives. And C is statically typed. What you try does not make any sense. It is an XY problem. What do you want to solve? Commented Jun 13, 2017 at 17:07
  • The preprocessor is a compile-time thing, that runs in a separate phase before the actual compilation takes place. The preprocessor uses it's own separate language, and have no concept of C variables. Commented Jun 13, 2017 at 17:09
  • Furthermore, there's no such thing as a default type. Commented Jun 13, 2017 at 17:09
  • So the only way to do it parse my own files? I am trying to create my own object type system in C. If I have an unknown void* and I know the data type by integer code then I want to be able to cast the void*. Commented Jun 13, 2017 at 17:14
  • It's not really clear what "it" is - what's a more realistic example of the problem you're trying to solve here? Commented Jun 13, 2017 at 17:16

1 Answer 1

3

What you want to do isn't possible with macros. They only do compile time text substitution, while what you want depends on runtime values.

If you want to effectively have a variable with a variant type, use a union:

struct var_type {
    int type;
    union {
        int i;
        double d;
    } value;
};

int main(int argc, char* argv[]) {
    struct var_type value = { DOUBLE_TYPE, { d = 0.5f }};

    switch (value.type) {
    case DOUBLE_TYPE:
        printf("%f\n", value.value.d);
        break;
    case INT_TYPE:
        printf("%d\n", value.value.i);
        break;
    default:
        printf("%d\n", value.value.i);
        break;
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I want to be able to cast a void* to a specific type known by the integer code.
You can't do that @eat_a_lemon
@eat_a_lemon Then check the type and cast it to that type.
@dbush yea I guess the union replaces void* with a list of known types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.