473,395 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

how do I pass a generic comparison function?

Howdy,

How do I pass some function a generic comparison
function? I figured out one non-generic case, but
since this code got parameter declarations in two places,
it's obviously not generic.

TIA

#include <stdio.h>

char comp1 ( int, int );
char comp2 ( char, char );
char comp3 ( char*, char* );

char comp1 ( int i1, int i2 ) {
if (i1 == i2) {
return '=';
} else if (i1 > i2) {
return '>';
} else {
return '<';
}
}

/* comp2 & comp3 omitted for brevity */

int some_func ( char (*comp)(int,int)) {
putchar((*comp) (7,8));
putchar((*comp) (8,8));
putchar((*comp) (8,7));
return 0;
}

int main () {
int i;
i = some_func((char (*)(int, int))(comp1));
return 0;
}
Nov 14 '05 #1
6 4432
aurgathor <sp*****@if-you.com> wrote:
How do I pass some function a generic comparison
function? I figured out one non-generic case, but
since this code got parameter declarations in two places,
it's obviously not generic. #include <stdio.h> char comp1 ( int, int );
char comp2 ( char, char );
char comp3 ( char*, char* ); char comp1 ( int i1, int i2 ) {
if (i1 == i2) {
return '=';
} else if (i1 > i2) {
return '>';
} else {
return '<';
}
} /* comp2 & comp3 omitted for brevity */ int some_func ( char (*comp)(int,int)) {
putchar((*comp) (7,8));
putchar((*comp) (8,8));
putchar((*comp) (8,7));
return 0;
} int main () {
int i;
i = some_func((char (*)(int, int))(comp1));
return 0;
}


Did you have a look at how it's done with the qsort() function? It
expects (as it's fourth argument) a function that has two 'const
void *' arguments. And I guess that's the only way to make the
function as generic as possible, i.e. you can pass all kinds of
data types to the comparison functions that way. If you use that
you would have something like

#include <stdio.h>

char cmp_as_ints( const void *a, const void *b ) {
if ( * ( int * ) a == * ( int * ) b )
return '=';
else if ( * ( int * ) a < * ( int * ) b )
return '<';
return '>';
}

int some_func( char ( *cmp )( const void *, const void * ) ) {
int dummy1 = 7, dummy2 = 8;
putchar( cmp( &dummy1, &dummy2 ) );
dummy1 = 8;
putchar( cmp( &dummy1, &dummy2 ) );
dummy2 = 7;
putchar( cmp( &dummy1, &dummy2 ) );
return 0;
}

int main( void ) {
int i = some_func( cmp_as_ints );
return 0;
}

Since you have to pass pointers to the comparison function you unfor-
tunately need two dummy variables in some_func() to be able to pass
their addresses. BTW, when you call a function via a function pointer
you can but don't have to dereference the function pointer, so both

cmp( &var1, &var2 )

and

( * cmp )( &var1, &var2 )

are perfectly valid ways to call the function 'cmp' points to.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #2
aurgathor wrote:

How do I pass some function a generic comparison
function? I figured out one non-generic case, but
since this code got parameter declarations in two places,
it's obviously not generic.

#include <stdio.h>

char comp1 ( int, int );
char comp2 ( char, char );
char comp3 ( char*, char* );

char comp1 ( int i1, int i2 ) {
if (i1 == i2) {
return '=';
} else if (i1 > i2) {
return '>';
} else {
return '<';
}
}

/* comp2 & comp3 omitted for brevity */
int some_func ( char (*comp)(int,int)) {
putchar((*comp) (7,8));
putchar((*comp) (8,8));
putchar((*comp) (8,7));
return 0;
}

int main () {
int i;
i = some_func((char (*)(int, int))(comp1));
return 0;
}


You use void *. To compare ints:

int cmpint(void *left, void *right)
{
int *leftitem = left;
int *rightitem = right;

if (leftitem > rightitem) return '>';
else if (leftitem < rightitem) return '<';
else return '=';
|

and functions to compare other types need only vary the name and
the types of the local pointers. The calling will only vary the
name of the function passed:

typedef int cmpfunct(void *, void *);

void foo(cmpfunct cmp)
{
... cmp(leftthing, rightthing);
}

....
foo(cmpint);

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #3
You use void *. To compare ints:

int cmpint(void *left, void *right)
{
int *leftitem = left;
int *rightitem = right;

if (leftitem > rightitem) return '>';
else if (leftitem < rightitem) return '<';
else return '=';
|

should this not be
if( *leftitem > *rightitem) return '>';
or am i overlooking something??

Regards

Mike

Nov 14 '05 #4
Michael wrote:
You use void *. To compare ints:

int cmpint(void *left, void *right)
{
int *leftitem = left;
int *rightitem = right;

if (leftitem > rightitem) return '>';
else if (leftitem < rightitem) return '<';
else return '=';
}

should this not be
if( *leftitem > *rightitem) return '>';
or am i overlooking something??


Yes and no respectively. The dog ate the asterisks.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #5
On Sat, 26 Feb 2005 04:21:38 -0800, "aurgathor" <sp*****@if-you.com>
wrote:
Howdy,

How do I pass some function a generic comparison
function? I figured out one non-generic case, but
since this code got parameter declarations in two places,
it's obviously not generic. <snip> char comp1 ( int, int );
char comp2 ( char, char );
char comp3 ( char*, char* ); <snip: definition of comp1>
int some_func ( char (*comp)(int,int)) {

<snip: use (*comp)( 2 ints )>

Several others have given specific answers using void*. That's usually
the simplest way but not the only one. What matters is that type of
parameters declared by the routine is the same as that declared to the
code that does the call (here through a pointer passed as parameter).

For scalar types there are hierarchies where a 'higher' type can
(always) handle the values of a 'lower' one, which you can then
convert/cast back if and when desired. For example long can handle any
int and int any short, and short any char if char is signed always and
even unsigned on 'normal' (8-bit) machines. double can handle any
float. void * (perhaps qualified) can handle any data pointer; so can
char * but it doesn't convert silently.

More generally but clumsily, you can create and use a union type. This
requires creating dummy objects at the point of 'anonymization' in
C90; in C99 you can use a compound literal, and in GCC as an extension
you can just cast to a union type that has a suitable member. This
does require that all types to be used be known at coding time; with
void * you can later (maybe even dynamically) add (instances of) new
types that pass through unchanged middle code.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #6

"Dave Thompson" <da*************@worldnet.att.net> schreef in bericht
news:7b********************************@4ax.com...
On Sat, 26 Feb 2005 04:21:38 -0800, "aurgathor" <sp*****@if-you.com>
wrote:
Howdy,

How do I pass some function a generic comparison
function? I figured out one non-generic case, but
since this code got parameter declarations in two places,
it's obviously not generic.

<snip>
char comp1 ( int, int );
char comp2 ( char, char );
char comp3 ( char*, char* );

<snip: definition of comp1>
int some_func ( char (*comp)(int,int)) {

<snip: use (*comp)( 2 ints )>

Several others have given specific answers using void*. That's usually
the simplest way but not the only one. What matters is that type of
parameters declared by the routine is the same as that declared to the
code that does the call (here through a pointer passed as parameter).

For scalar types there are hierarchies where a 'higher' type can
(always) handle the values of a 'lower' one, which you can then
convert/cast back if and when desired. For example long can handle any
int and int any short, and short any char if char is signed always and
even unsigned on 'normal' (8-bit) machines. double can handle any
float. void * (perhaps qualified) can handle any data pointer; so can
char * but it doesn't convert silently.

More generally but clumsily, you can create and use a union type. This
requires creating dummy objects at the point of 'anonymization' in
C90; in C99 you can use a compound literal, and in GCC as an extension
you can just cast to a union type that has a suitable member. This
does require that all types to be used be known at coding time; with
void * you can later (maybe even dynamically) add (instances of) new
types that pass through unchanged middle code.

- David.Thompson1 at worldnet.att.net


you cannot

The best thing you can do is using char * and use strcmp I think

Johan

Nov 14 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: gong | last post by:
hi i recently looked at alexandrescu's book on c++, and i found it pretty much unintelligible. i have a few points which i wonder about. 1. as a developer, it is important, from a bottom line...
15
by: Stig Brautaset | last post by:
Hi group, I'm playing with a little generic linked list/stack library, and have a little problem with the interface of the pop() function. If I used a struct like this it would be simple: ...
5
by: Metaman | last post by:
I'm trying to write a generic method to generate Hashcodes but am having some problems with (generic) collections. Here is the code of my method: public static int GetHashCode(object input) {...
22
by: AB | last post by:
Hello All, I'm trying to replicate a general purpose sort function (think qsort) void sort(void *arr, const int num, size_t size, int (*cmp)(void *a, void *b)) { int i = 0 ; int j = 0 ;
3
by: kim.nolsoee | last post by:
Hi I want to use the Dictionary Classs that will load my own class called KeyClass used as TKey. Here is the code: public class Dictionary { public static void Main()
3
by: =?Utf-8?B?R0I=?= | last post by:
I have created a small program that illustrates the problem. I would know how to address the fields that I want to sort on in the greaterThan comparison. Anybody who knows?? using System; ...
6
by: =?Utf-8?B?emlubw==?= | last post by:
I'm trying to pass a delegate as parameter but the code below does not compile. It display an error: 'AddressOf operand must the name of a method(without parantheses)' How can I make it work. ...
14
by: Siegfried Heintze | last post by:
Why does VB.NET V2 force me to pass by value for my set function? When I try to change it to const byref it gives me a syntax error. It seems very inefficient to be passing strings around by value...
2
by: puzzlecracker | last post by:
Unlike C++, in Csharp you're only allowed to compare a generic type T with null, if the method it's passed in not implementing IComparable<Tor , IEquatable<T(still don't know why we need these...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.