How do I handle these typedef's without warnings?

Viewed 51

I have some if statements to handle the value_type in different ways. If INT is defined then value_type is an integer, but if CHAR is defined value_type is a string. How can I handle this so I don' get any errors or warnings ?

I defined value_type like this:

#ifdef INT
typedef int value_type;
#define TYPEMODE 1
#endif

#ifdef CHAR
typedef char value_type[80];
#define TYPEMODE -1
#endif

I handled it like this in functions:

int functionName(value_type val) {
   if (TYPEMODE == 1) {
      val = 5;
   }
   if (TYPEMODE == -1) {
      strcpy(val, "hi");
   }
   return 0;
}

If I define INT it gives me a warning for strcpy, if I define CHAR it gives me a warning for val = 5.

Is there a better way to handle this that won't give me any warnings with gcc -Wall file.c -o file?

4 Answers
int functionName(value_type val) {
   if (TYPEMODE == 1) {
      val = 5;
   }
   if (TYPEMODE == -1) {
      strcpy(val, "hi");
   }
   return 0;
}

can be

int functionName(value_type val) {
#if TYPEMODE == 1
      val = 5;
#endif
#if TYPEMODE == -1
      strcpy(val, "hi");
#endif
   return 0;
}

You should modify both code fragments this way:

In the declaration file:

#ifdef INT
typedef int value_type;
#define TYPEMODE  1
#endif

#ifdef CHAR
typedef char value_type[80];
#define TYPEMODE  (-1)   // use parentheses to avoid operator precedence issues
#endif

In the code:

int functionName(value_type val) {
#if TYPEMODE == 1
   val = 5;
#elif TYPEMODE == -1
   strcpy(val, "hi");
#endif
   return 0;
}

Because you're flagging on preprocessor flags, it's best to let the preprocessor do the check:

int functionName(value_type val) {
#if TYPEMODE == 1
    val = 5;
#elif TYPEMODE == -1
    strcpy(val, "hi");
#endif
   return 0;
}

Just to offer an alternative option: have you considered ditching the #defines and just using a union?

#include <stdio.h>

typedef union {
    int number;
    char text[50];
} value_type;

void functionName(value_type val, int typemode) {
    if (typemode == 1) {
        val.number = 5;
    } else if (typemode == -1) {
        strcpy(val.text, "hi");
    }
    return 0;
}

int main(void) {
    value_type myval;
    functionName(myval, 1);
    functionName(myval, -1);
    return 0;
}
Related