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 don't have any 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 it doesn't work:
void better (void a, void b)
{
if (a > b)
return a;
else if (b > a)
return b;
}
What is the right way to do this? This is not my exact assignment; I just want to understand how it works.
You're trying to create a sort of generalized function that takes arguments of some type and returns the larger value, in the same type.
The 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 just isn't any 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 it doesn't do it with pure C constructs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With