user2520119
user2520119

Reputation: 183

How to use different datatype variable based on condition?

I have following two structure

typedef struct {

int day;

char action [10];

}DataType1;

and

typedef struct {

int day;

char action [50];

}DataType2;

Now i have to use only one structure data type based on some condition. I have done something like this

void *ptr;
DataType1 var1;
DataType2 var2;

if (validCondition  == true)
{
    ptr = &var1;
}
else
{
   ptr = &var2;
}
//Used ptr in remaining code

But using this code i fill that may be there is some design flew in my code that's why i need this type trick but anyway i need that. I thought some different way also but i have doubt how it works

if (validCondition  == true)
{
    #define GENERIC_TYPE DataType1;
}
else
{
   #define GENERIC_TYPE DataType2;
}

GENERIC_TYPE myVar;
//use myVar in remaining code 

As i know line starting from symbol # consider as processor command and it will be known and replaced at compile time. But here i have if condition in which validCondition changed run time and according that #define defined.

So in this case how processor will work?

Also any one have batter idea to define different data type variable based on condition?

Upvotes: 2

Views: 866

Answers (2)

babon
babon

Reputation: 3774

How about keeping only one struct:

typedef struct {
    int day;
    char *action;
} DataType;

And then based on some condition, invoke malloc() with the proper number of bytes you need:

DataType dt;
if (checkWhateverCondionYouWant)
    dt.action = malloc(someSize);

HTH.

Upvotes: 0

Roland Illig
Roland Illig

Reputation: 41686

You could define a wrapper type for these data types:

struct DayAction {
  int day;
  char *action;
  size_t actionlen;
};

Then, have a variable of that type and, depending on your condition, fill in the fields of that variable:

struct DayAction day_action;

if (condition()) {
  day_action.day = dt1.day;
  day_action.action = dt1.action;
  day_acion.actionlen = sizeof dt1.action;
}

After that, you can operate on day_action, since it points into the original data.

If you need to change the dt1.day, make DayAction.day a pointer. If you don’t need to change the action, make DayAction.action a const char *.

Upvotes: 1

Related Questions