473,756 Members | 7,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Way to determine type of variable?

I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want.

int main(void)
{
int i=7;
char *s="/etc/filesystems";

generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
}

should return:
7
/etc/filesystems
Hello
2048

so...

void generic( ???????)
{
???
}

I have looked at sprintf, varargs etc.

Could someone point me in the right direction?

Thanks,

Walter
Nov 14 '05 #1
21 10671
Walter L. Preuninger II <wa*****@texram p.net> wrote:
I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want. int main(void)
{
int i=7;
char *s="/etc/filesystems"; generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
} should return:
7
/etc/filesystems
Hello
2048 so... void generic( ???????)
{
???
} I have looked at sprintf, varargs etc. Could someone point me in the right direction?


Sorry, but there's no right direction. Types are a compile
time concept and the type information is only used during the
compilation and is only implicitely contained in the resulting
executable (i.e. why certain machine instructions are used and
not others). So at run-time the type information does not exist
anymore and thus such generic functions are impossible - there
is no additional type information attached to a variable once
the code has been compiled.

All that is left is the question why you need such generic
functions (beside that it sometimes would be nice to have
them) - perhaps there's a different solution to your problem.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #2
"Walter L. Preuninger II" <wa*****@texram p.net> wrote in
news:l5******** ***@10.224.0.25 4:
I would like to write a generic procedure that will take string or
numeric variables. I can not think of a way to make this more clear
except to show what I want.

int main(void)
{
int i=7;
char *s="/etc/filesystems";

generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
}

should return:
7
/etc/filesystems
Hello
2048

so...

void generic( ???????)
{
???
}

I have looked at sprintf, varargs etc.

Could someone point me in the right direction?


Hate to say it, but C++ is the right direction for this. This is one of
those things, that in C, is rather clumsy to do, error prone, and doesn't
look very nice in the end.

--
- Mark ->
--
Nov 14 '05 #3

"Walter L. Preuninger II" <wa*****@texram p.net> ÓÏÏÂÝÉÌ/ÓÏÏÂÝÉÌÁ × ÎÏ×ÏÓÔÑÈ
ÓÌÅÄÕÀÝÅÅ: news:l5******** ***@10.224.0.25 4...
I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want.

int main(void)
{
int i=7;
char *s="/etc/filesystems";

generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
}

should return:
7
/etc/filesystems
Hello
2048

so...

void generic( ???????)
{
???
}

I have looked at sprintf, varargs etc.

Could someone point me in the right direction?

Thanks,

Walter


You'll need to implement polymorphism or use macrosses. If you really need
this facilities, try using C++ instead. You CAN implement something like
this in C, see http://ldeniau.home.cern.ch/ldeniau/html/oopc/oopc.html
for example

--
vir
Nov 14 '05 #4

"Walter L. Preuninger II" <wa*****@texram p.net> a écrit dans le message de
news:l5******** ***@10.224.0.25 4...
I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want.

int main(void)
{
int i=7;
char *s="/etc/filesystems";

generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
}

should return:
7
/etc/filesystems
Hello
2048

so...

void generic( ???????)
{
???
}

I have looked at sprintf, varargs etc.

Could someone point me in the right direction?

Thanks,

Walter


This is not possible with standard C.
Generic functions aren't part of the standard language.

The lcc-win32 compiler implements generic functions
exactly like you want, but it isn't standard C, i.e. generic
functions are an *extension* of the language.

If you do not mind using extensions go to
http://www.cs.virginia.edu/~lcc-win32.

Within standard C you can write a function like this:

#define INTEGER 1
#define STRING 2
#define DOUBLE 3
union data {
int Type;
int integer;
double doublefloat;
float floatfloat;
char *string;
// add other cases here
};

void generic(union data Data)
{
switch (Data.Type) {
case INTEGER:
printf("%d\n",D ata.integer);
break;
case STRING:
printf("%s\n",D ata.string);
break;
// Add the other cases here
}
}

int main(void)
{
union data Data;
Data.integer = 7;
Data.Type = INTEGER;
generic(Data);
Data.string = "/etc/path";
Data.Type = STRING;
generic(Data);
Data.Type = DOUBLE;
Data.doublefloa t = 67.987;
generic(DOUBLE, Data);
/// etc
}

}

Nov 14 '05 #5
Walter L. Preuninger II wrote:
I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want.

int main(void)
{
int i=7;
char *s="/etc/filesystems";

generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
}

should return:
7
/etc/filesystems
Hello
2048

so...

void generic( ???????)
{
???
}

I have looked at sprintf, varargs etc.

Could someone point me in the right direction?


The best you can get is something along the lines of

enum Type { INT, STRING, /* others ... */ );
generic(INT, i);
generic(STRING, s);
generic(STRING, "Hello");
generic(INT, 2048);

Or with a repackaging of essentially the same idea, you could get

struct { enum Type type;
union { int i; char *s; /* others ... */ } value;
} args;
args.type = INT; args.value.i = i; generic(args);
args.type = STRING; args.value.s = s; generic(args);
args.value.s = "Hello"; generic(args);
args.type = INT; args.value.i = 2048; generic(args);

Neither of these seems especially attractive, nor do any of
the other variations I can think of. They're ugly, they're
clumsy, and they're error-prone -- the compiler will not
detect the mistakes in

/* first form */
generic(STRING, 42);

/* second form */
args.type = INT; args.value.s = "Boom!"; generic(args);

The fundamental problem is that C is a statically-typed
language, meaning that the type of every expression is fixed
at compile time. True, <stdarg.h> (not <varargs.h>, BTW) can
evade this requirement, but only briefly: In order to access
the arguments corresponding to `...', you must use an expression
whose type is known and immutable. C is not Lisp.

--
Er*********@sun .com

Nov 14 '05 #6
jacob navia wrote:

Within standard C you can write a function like this:

#define INTEGER 1
#define STRING 2
#define DOUBLE 3
union data {
int Type;
int integer;
double doublefloat;
float floatfloat;
char *string;
// add other cases here
};


Uh, that doesn't look right. Shouldn't it be something
more like:

struct data
{
int Type;
union values
{
int integer;
double doubleFloat;
float floatFloat;
char *string
// add other cases here
};
};

If the Type is in the union, then wouldn't Type and
integer overwrite each other?

Drew
Nov 14 '05 #7
<Je***********@ physik.fu-berlin.de> wrote in message
news:2l******** ****@uni-berlin.de...
Walter L. Preuninger II <wa*****@texram p.net> wrote:
[snip]
All that is left is the question why you need such generic
functions (beside that it sometimes would be nice to have
them) - perhaps there's a different solution to your problem.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de


I needed a generic error printing routine, better than what perror()
provides.

incomplete code follows

char *filename="X";
char *buffer;
int size=65536;

file=fopen(file name,"rt");
if (file==NULL)
{
xerror("fopen failed",filenam e);
exit(1);
}
buffer=(char *)malloc(size);
if(buffer == NULL) {
xerror("malloc failed, size=",size);
}

I guess I could use sprintf to fill a buffer and print/pass that, but I
wanted to lessen the amount of code written.

I have written a macro for xerror that does pass argv[0], __FILE__, __LINE__
and errno to produce
../test:test.c:15: fopen failed:X for the fopen example above.

Thanks,

Walter

Nov 14 '05 #8
"Walter L. Preuninger II" wrote:

I would like to write a generic procedure that will take string or numeric
variables. I can not think of a way to make this more clear except to show
what I want.

int main(void)
{
int i=7;
char *s="/etc/filesystems";

generic(i);
generic(s);
generic("Hello" );
generic(2048);
exit(0);
}

should return:
7
/etc/filesystems
Hello
2048

so...

void generic( ???????)
{
???
}

I have looked at sprintf, varargs etc.

Could someone point me in the right direction?

Something like sprintf() is about as close as you are going to get. You
can use a variadic function or pass in void pointers, but in any case
you'll need to let the function know about the type.

One way would be a typed data struct:
struct data
{
void *datap;
int type;
};

Then set type when the data is created.


Brian Rodenborn
Nov 14 '05 #9
AAAAAArg!!!!

Right!

4 eyes see more than just two. Another proof of that old
wisdom.

It must be a structure with the type *outside* the union.

Sorry about this bug!

jacob
Nov 14 '05 #10

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

Similar topics

17
6149
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number. "Decimal Number" sometimes serves to distinguish Base 10 numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal Number" serves to differentiate a number from an integer. For the rest of this post I shall only use either...
3
2585
by: Shahid Juma | last post by:
Hello All, This may be a trivial question, but I was wondering how can you determine if a value contains an Integer or Float. I know there is a function called IsNumeric, however you can't determine what type it is. Thanks for the help, Shahid
4
3057
by: MCollins | last post by:
trying to determine a variable type, specifically that a variable is an integer. i tried using type(var) but that only seemed to produce a response in the command line. is there a built in python function to determine if a variable is an integer?
14
24434
by: J. Jones | last post by:
Suppose the following: class MyContainer : System.Collections.CollectionBase { //... } (where CollectionBase implements IList, ICollection) How do I determine if a type (such as MyContainer) derives from IList?
3
1170
by: M Shafaat | last post by:
Hi! I want to write C# code by which I can determine the name of an object and/or variable at run-time. VS design windows does it when you drag a control onto your form. It uses the name of the control's type and adds a number to it and creates a name for the object, like "button2". Regards M Shafaat
16
3425
by: Jm | last post by:
Hi All Is it possible to determine who is logged onto a machine from inside a service using code in vb.net ? I have found some code that seems to work under vb6, but doesnt under .NET ? Any help is greatly appreciated Thanks
1
1567
by: tshad | last post by:
I have some code to go through a session collection for my error page routine and I get an error on my objects that I store in session variables. Dim strName as String Dim iLoop as Integer For Each strName in Session.Contents trace.warn(strName & " - " & Session.Contents(strName)) Next
5
6843
by: MLH | last post by:
Suppose MyName, a string variable equals "frmEnterClients". How can I determine ... 1) if frmEnterClients exists as an object in the database? 2) what type of object is it (tbl, qry, frm, rpt, mac, mod)?
8
1703
by: Ole | last post by:
If I define a class and create a instant of it like e.g.: UserClass instantName = new UserClass(); how do I then determine the defined name "instantName" in the UserClass e.g. in a method (or a property) like this: public void userFunction() { string Var = new string();
29
5115
by: garyusenet | last post by:
I'm trying to investigate the maximum size of different variable types. I'm using INT as my starting variable for exploration. I know that the maximum number that the int variable can take is: 65,535. But i'm trying to write a program to test this, assuming I didn't know this number in advance. I came up with the following but have two questions. Maybe someone can help? using System; using System.Collections.Generic; using System.Text;
0
9894
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
9541
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...
0
8542
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6390
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
4955
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
5156
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3651
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
3141
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2508
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.