Вопрос

I have to do a function that takes in a variable of any data type and return a variable of the same data type. I have no idea how to do this all I know is that I have to use void as a data type of my parameters so all I have is this and obviously is doesn't work:

void better (void a, void b)
{
    if ( a > b )
        return a;
    else if ( b > a )
        return b;
}

So my question would be what is the right way to do this? This is not my exact assignment I just want to understand how it works.

Это было полезно?

Решение

Perhaps it would help to first identify compare methods:

typedef enum CMPTYPE_E
   {
   CMPTYPE_STRCMP,
   CMPTYPE_INT
// ..etc
   } CMPTYPE_T;

Then, a method can be supplied to compare each defined type:

void *better (void *a, void *b, CMPTYPE_T cmpType)
   {
   switch(cmpType)
      {
      case CMPTYPE_STRCMP:
         return(strcmp(a,b) > 1 ? a : b);

      case CMPTYPE_INT:
         return((*((int *)a) > *((int *)b)) ? a : b);         

 //   ...etc
      }
   }        

Другие советы

What you're trying to do is create a sort of generalized function that takes arguments of some type and returns the larger value, in the same type.

Problem is, you actually can't do this in C. Although it's true that several C primitive types can be compared using the same kind of > logic, not all of them can be compared meaningfully like that, and even if they could, the compiler won't let you do this-- there's just no way to say "argument with unknown type" and "return whatever type the argument was".

C requires you to define the type explicitly, which usually means creating a different version of this function for every type you want to support. In other words, make a better_int function, and a better_float function, etc, and then call the appropriate one.


In this case, it's also possible to use other compiler features, called macros, to essentially autogenerate this comparison code for you right before compiling the code. This can achieve your goal, but doesn't do it with pure C constructs. Feel free to ask more about this approach if you still want to solve this problem this way.

If you are limited to C, you can use void* as your parameter types and return type as well. This works, but there is no protection from the compiler if you pass in the wrong type(s). You have to take care to manage the variables and make sure that if you pass in a char* for instance, that the function handles it as such and not as something else.

Also note that you are now dealing with pointers and addresses rather than primitive types. This introduces a new level of complication to your logic, especially if you allocate memory (e.g. malloc) for the return value that must be later freed.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top