473,657 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to create a function that can be applied to all type of variables?

Hello !

I was wondering how to create a function that can be applied to all
type of variables?
If we use for example, sortList(void *obj), we can not do the
comparison of 2 strcut.

Faithfully yours,
Try Kret.
Nov 14 '05 #1
5 1846
nrk
Try Kret wrote:
Hello !

I was wondering how to create a function that can be applied to all
type of variables?
Not exactly sure what you want here. Do you want to pass just a pointer of
any type to your function? If so, void * coupled with another formal
parameter that tells you the type is one easy approach. There are no
"magic" solutions here. You have to slog it out and write the code for
both passing the type as well as the data and handling both inside your
function. For instance:

int sortList(int type, void *obj) {
switch ( type ) {
case 1:
{ /* obj has type pointer-to-int */
int *data = obj;
...
}
break;
case 2:
{
/* obj has type pointer-to-float */
float *data = obj;
...
}
break;
...
}
}

void doStuff() {
int *intlist;

...

sortList(1, intlist);
}

You get the idea. If you're tempted to do this however, I would like you to
consider writing separate functions to handle each type rather than this
approach.

If all you're looking for is general purpose sorting of data, consider using
the library's qsort function. All you need to provide is the comparison
function for the data you want to sort. For instance, to sort an array of
integers:

#include <stdio.h>

int cmpints(const void *in1, const void *in2) {
const int *i1 = in1;
const int *i2 = in2;

if ( *i1 < *i2 )
return -1;
if ( *i1 > *i2 )
return 1;
return 0;
}

void sortList(size_t sz, int *list) {

qsort(list, sz, sizeof *list, cmpints);

}

If you need to pass an arbitrary number of parameters of arbitrary types, a
format string based varargs function along the lines of the *printf/*scanf
family can be used.
If we use for example, sortList(void *obj), we can not do the
comparison of 2 strcut.

strcut? Did you mean strcmp? You can write a wrapper function that calls
strcmp, and then use it along with qsort.

-nrk.
Faithfully yours,
Try Kret.


Nov 14 '05 #2
On Mon, 22 Dec 2003 23:58:50 -0500, Try Kret wrote:
Hello !

I was wondering how to create a function that can be applied to all type
of variables?
If we use for example, sortList(void *obj), we can not do the comparison
of 2 strcut.


If void * is a pointer to an array of pointers you would then know
that each element is sizeof(void *). You could then provide for the
specification of a comparison function like:

typedef int (*compare_fn)(c onst void *object1, const void *object2);

and then call sortList(void *obj, compare_fn cmp).

Or you could specify the size of each element and use a comparison
function like sortList(void *obj, size_t elemsiz, compare_fn cmp). This
would be *very roughly*:

void
sortList(void *obj, size_t elemsiz, compare_fn cmp)
{
unsigned char *p1 = obj, *p2;

sorting loop {
compare_fn((voi d *)p1, p2)
p1 += elemsiz;
}
}
Nov 14 '05 #3
nrk <ra*********@de adbeef.verizon. net> wrote in message news:<wI******* **********@nwrd dc02.gnilink.ne t>...
Try Kret wrote:
Hello !

I was wondering how to create a function that can be applied to all
type of variables?


Not exactly sure what you want here. Do you want to pass just a pointer of
any type to your function? If so, void * coupled with another formal
parameter that tells you the type is one easy approach. There are no
"magic" solutions here. You have to slog it out and write the code for
both passing the type as well as the data and handling both inside your
function. For instance:

int sortList(int type, void *obj) {
switch ( type ) {
case 1:
{ /* obj has type pointer-to-int */
int *data = obj;
...
}
break;
case 2:
{
/* obj has type pointer-to-float */
float *data = obj;
...
}
break;
...
}
}

void doStuff() {
int *intlist;

...

sortList(1, intlist);
}

You get the idea. If you're tempted to do this however, I would like you to
consider writing separate functions to handle each type rather than this
approach.

If all you're looking for is general purpose sorting of data, consider using
the library's qsort function. All you need to provide is the comparison
function for the data you want to sort. For instance, to sort an array of
integers:

#include <stdio.h>

int cmpints(const void *in1, const void *in2) {
const int *i1 = in1;
const int *i2 = in2;

if ( *i1 < *i2 )
return -1;
if ( *i1 > *i2 )
return 1;
return 0;
}

void sortList(size_t sz, int *list) {

qsort(list, sz, sizeof *list, cmpints);

}

If you need to pass an arbitrary number of parameters of arbitrary types, a
format string based varargs function along the lines of the *printf/*scanf
family can be used.
If we use for example, sortList(void *obj), we can not do the
comparison of 2 strcut.


strcut? Did you mean strcmp? You can write a wrapper function that calls
strcmp, and then use it along with qsort.

-nrk.
Faithfully yours,
Try Kret.


Thank you very much. I did not mean strcmp, instead I mean we can not
compare 2 structure data type. If we pass structure as arguments, is
there any problem we the instruction of comparison is executed?
ex: struct elt{
void *obj;
elt *next;
};
typedef (struct elt *) list;
list *l;

Can we call: void sortList(*l); without error?
Nov 14 '05 #4
Michael B Allen <mb*****@ioplex .com> wrote in message news:<pa******* *************** ************@io plex.com>...
On Mon, 22 Dec 2003 23:58:50 -0500, Try Kret wrote:
Hello !

I was wondering how to create a function that can be applied to all type
of variables?
If we use for example, sortList(void *obj), we can not do the comparison
of 2 strcut.


If void * is a pointer to an array of pointers you would then know
that each element is sizeof(void *). You could then provide for the
specification of a comparison function like:

typedef int (*compare_fn)(c onst void *object1, const void *object2);

and then call sortList(void *obj, compare_fn cmp).

Or you could specify the size of each element and use a comparison
function like sortList(void *obj, size_t elemsiz, compare_fn cmp). This
would be *very roughly*:

void
sortList(void *obj, size_t elemsiz, compare_fn cmp)
{
unsigned char *p1 = obj, *p2;

sorting loop {
compare_fn((voi d *)p1, p2)
p1 += elemsiz;
}
}


Talk about this function:
typedef int (*compare_fn)(c onst void *object1, const void *object2);

For example:
struct student{
int id;
char name[20];
int age;
}stud1, stud2;

If I call: compare_fn((str uct student)stud1, (struct student)stud2);
what will be the problem?
Nov 14 '05 #5
Try Kret wrote:

Michael B Allen <mb*****@ioplex .com> wrote in message news:<pa******* *************** ************@io plex.com>...
On Mon, 22 Dec 2003 23:58:50 -0500, Try Kret wrote:
Hello !

I was wondering how to create a function that can be applied to all type
of variables?
If we use for example, sortList(void *obj), we can not do the comparison
of 2 strcut.


If void * is a pointer to an array of pointers you would then know
that each element is sizeof(void *). You could then provide for the
specification of a comparison function like:

typedef int (*compare_fn)(c onst void *object1, const void *object2);

and then call sortList(void *obj, compare_fn cmp).

Or you could specify the size of each element and use a comparison
function like sortList(void *obj, size_t elemsiz, compare_fn cmp). This
would be *very roughly*:

void
sortList(void *obj, size_t elemsiz, compare_fn cmp)
{
unsigned char *p1 = obj, *p2;

sorting loop {
compare_fn((voi d *)p1, p2)
p1 += elemsiz;
}
}


Talk about this function:
typedef int (*compare_fn)(c onst void *object1, const void *object2);

For example:
struct student{
int id;
char name[20];
int age;
}stud1, stud2;

If I call:
compare_fn((str uct student)stud1, (struct student)stud2);
what will be the problem?


compare_fn(&stu d1, &stud2);

--
pete
Nov 14 '05 #6

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

Similar topics

8
2793
by: Nick Coghlan | last post by:
Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def _build_used(): .... y = x + 1 .... return x, y ....
10
1456
by: Ron_Adam | last post by:
I'm trying to figure out how to test function arguments by adding a decorator. @decorate def func( x): # do something return x This allows me to wrap and replace the arguments with my own, but not get the arguments that the original function received.
4
24171
by: Andrew V. Romero | last post by:
I have been working on a function which makes it easier for me to pull variables from the URL. So far I have: <script language="JavaScript"> var variablesInUrl; var vArray = new Array(); function loadUrlVariables() { varString = location.search;
2
3048
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is what I'm hoping to achieve. I've never before had to use Javascript closures, but now I do, so I'm making an effort to understand them. I've been giving this essay a re-read: http://jibbering.com/faq/faq_notes/closures.html
18
2708
by: Steven Bethard | last post by:
I've updated the PEP based on a number of comments on comp.lang.python. The most updated versions are still at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html In this post, I'm especially soliciting review of Carl Banks's point (now discussed under Open Issues) which asks if it would be better to have the create statement translated into:
5
2335
by: mancomb | last post by:
Hi, I'm curious to the syntax of calling member functions through pointers of classes returned through the -operator. For example (excuse the crude incomplete code); Here are the classes: Class Foo{
14
1545
by: Nickolay Ponomarev | last post by:
Hi, Why does http://www.jibbering.com/faq/ uses new Function constructor instead of function expressions (function(...) { ... }) when defining new functions? E.g. for LTrim and toFixed. Is the reason that you want to avoid accidental closures? Or does some obscure browser does not support function expressions? This just looks weird, given that http://www.jibbering.com/faq/#FAQ4_40 says to only use eval() (which is not really much...
6
2897
by: Lighter | last post by:
How to read "The lvalue-to-rvalue, array-to-pointer, and function-to- pointer standard conversionsare not applied to the left expressions"? In 5.18 Comma operator of the C++ standard, there is a rule: "The lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversionsare not applied to the left expressions" I could not understand what the rule means. I also searched the web and the groups and got nothing.
4
6901
by: Vlad | last post by:
I am having problems using the file.create method within a function that is called when looping through an array of filepaths. If I call my function with a hardcoded file path --C:\Temp.txt the function creates the file as expected. When I loop through my array I get the error - "ArgumentException was unhandled - Illegal characters in path" The value "C:\Temp.txt" is the first value in the array - as it works
0
8305
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8823
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8603
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1604
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.