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
21 10672
The version I posted contained a serious error:
The type of the union should not be stored in the
union itself!
Here is a corrected version.
Sorry for this error. Within standard C you can write a function like this:
#define INTEGER 1 #define STRING 2 #define DOUBLE 3 struct data {
int Type; // Type OUTSIDE the union
union u { int integer; double doublefloat; float floatfloat; char *string; // add other cases here }u; };
void generic(union data Data) { switch (Data.Type) { case INTEGER: printf("%d\n",D ata.u.integer); break; case STRING: printf("%s\n",D ata.u.string); break; // Add the other cases here } }
int main(void) { union data Data; Data.u.integer = 7; Data.Type = INTEGER; generic(Data); Data.u.string = "/etc/path"; Data.Type = STRING; generic(Data); Data.Type = DOUBLE; Data.u.doublefl oat = 67.987; generic(DOUBLE, Data); /// etc }
Walter L. Preuninger II <wa*****@texram p.net> wrote: 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 guess the cleanest way would be to add printf-like format
information to the string you send to xerror(), e.g.
xerror( "fopen failed for:%s", filename );
xerror( "malloc failed: size=%ld", size );
etc. and in xerror() you then would have
#include <stdarg.h>
void xerror( const char *fmt, ... )
{
va_list ap;
/* Put printing argv[0], __FILE__ and __LINE__ in here */
va_start( ap, fmt );
vfprintf( stderr, fmt, ap );
va_end( ap );
}
It doesn't cost you too much in typing and works without lots of
complicated (and error prone) macros or extremely ugly code.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
"Walter L. Preuninger II" <wa*****@texram p.net> writes: 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
By "should return", I think you mean "should print".
so...
void generic( ???????) { ??? }
I have looked at sprintf, varargs etc.
You're asking about function overloading, which C doesn't support.
<OT>C++ does.</OT>
You can do something similar with variable argument lists
(<stdarg.h>), but you have to have an initial argument specifying the
type(s) of the following argument(s). For example, you could have
something like
generic(INT, i);
generic(STRING, s);
generic(STRING, "Hello");
generic(INT, 2048);
(given appropriate declarations of INT, STRING, etc.)
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
<Je***********@ physik.fu-berlin.de> wrote in message
news:2l******** ****@uni-berlin.de... Walter L. Preuninger II <wa*****@texram p.net> wrote:
[snip] /* Put printing argv[0], __FILE__ and __LINE__ in here */
only problem here is that __FILE__ and __LINE__ represent the filename and
line number of the source file, in which would be xerror.c and not main.c or
what ever, but thanks for the info and I will see how I can apply it to my
needs
Thanks!
Walter
"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.
So you should know that you can write a function
void generic(char *type, ...)
generic("int", 123);
generic("char *", "Hello");
etc.
Then in generic you decode the first argument, which tells you what to pass
to va_arg() to get the argument. If you try to write printf() it is done in
a similar manner, excpet that the format string uses a "%" specifier to tell
you the argument type instead of passing a name.
If you have any problem implementing the variable argument list, just post
back.
Walter L. Preuninger II <wa*****@texram p.net> wrote: <Je***********@ physik.fu-berlin.de> wrote in message news:2l******** ****@uni-berlin.de... Walter L. Preuninger II <wa*****@texram p.net> wrote:
[snip] /* Put printing argv[0], __FILE__ and __LINE__ in here */ only problem here is that __FILE__ and __LINE__ represent the filename and line number of the source file, in which would be xerror.c and not main.c or what ever, but thanks for the info and I will see how I can apply it to my needs
Unless you have a C99 compliant compiler, allowing macros with a
variable number of arguments, that's going to be more messy. The
simplest approach probably would be to define
#define AFL argv[0], __FILE__, __LINE__
and use it as
xerror( AFL, "File not found: %s", filename );
and declare xerror as
void xerror( const char *prog_name, const char *file_name, int line_number,
const char *fmt, .... );
That way you would get at the file name and line number without too
much hassle (well, it's not beautiful, but it should work). And if
you're too lazy to write that AFL stuff into code 'sed' or something
similar can be quite useful for such mindnumbing tasks;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Walter L. Preuninger II wrote: <Je***********@ physik.fu-berlin.de> wrote in message news:2l******** ****@uni-berlin.de...
Walter L. Preuninger II <wa*****@texram p.net> wrote:
[snip]
/* Put printing argv[0], __FILE__ and __LINE__ in here */
only problem here is that __FILE__ and __LINE__ represent the filename and line number of the source file, in which would be xerror.c and not main.c or what ever, but thanks for the info and I will see how I can apply it to my needs
If you have a C99-conforming compiler you can write
macros with variable numbers of arguments, and that eases
the task of adding __FILE__ and __LINE__ to an XERROR macro
that in turn invokes the xerror() function. Failing that,
gcc has its own pre-C99 way of writing "varargs macros."
And if even that isn't acceptable, you can use the dodge
described in Question 10.26 of the FAQ http://www.eskimo.com/~scs/C-faq/top.html
-- Er*********@sun .com
Walter L. Preuninger II wrote: <Je*********** @physik.fu-berlin.de> wrote:void xerror( const char *fmt, ... ) { /* Put printing argv[0], __FILE__ and __LINE__ in here */
only problem here is that __FILE__ and __LINE__ represent the filename and line number of the source file, in which would be xerror.c and not main.c
That's easily solved with a small macro wrapper for the function, which
would substitute the file and line number for the invocation, e.g.:
#define xerror( fmt, ... ) xerror( "%s:%d - " fmt, __FILE__, __LINE, \
__VA_ARGS__ )
However, this has several limitations (other than requiring C99 macros)
so I'm sure that you'll want to try to make something better. Perhaps,
even, something that doesn't affect the arguments to xerror...
--
++acr@,ka" Je***********@p hysik.fu-berlin.de writes:
[...] Unless you have a C99 compliant compiler, allowing macros with a variable number of arguments, that's going to be more messy. The simplest approach probably would be to define
#define AFL argv[0], __FILE__, __LINE__
and use it as
xerror( AFL, "File not found: %s", filename );
If it refers to argv[0], you can only use it within main() (assuming
the usual declarations).
You can have main() save the value of argv[0] to a global variable and
refer to that variable in the AFL macro.
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sam Dennis wrote: Walter L. Preuninger II wrote:
<Je********** *@physik.fu-berlin.de> wrote:
void xerror( const char *fmt, ... ) { /* Put printing argv[0], __FILE__ and __LINE__ in here */
only problem here is that __FILE__ and __LINE__ represent the filename and line number of the source file, in which would be xerror.c and not main.c
That's easily solved with a small macro wrapper for the function, which would substitute the file and line number for the invocation, e.g.:
#define xerror( fmt, ... ) xerror( "%s:%d - " fmt, __FILE__, __LINE, \ __VA_ARGS__ )
However, this has several limitations (other than requiring C99 macros) so I'm sure that you'll want to try to make something better. Perhaps, even, something that doesn't affect the arguments to xerror...
Another approach is to print the location information and
the error-specific information with two functions instead of
trying to do it all with one. In addition to Jens' xerror(),
you'd also write
void xwhere(const char *file, int line) {
fprintf (stderr, "%s line %d: ", file, line);
}
Then you'd use
#define XERROR xwhere(__FILE__ , __LINE__) , xerror
...
XERROR ("Can't open %s\n", filename);
XERROR ("Supercalifrag ilisticexpialid ocious!\n");
XERROR ("Invalid co-ordinates (%g,%g)\n", x, y);
You could, of course, dispense with xwhere() and call fprintf()
directly from the macro expansion, if you can be sure that
<stdio.h> has been included everwhere XERROR is used. And there
are other variations, too -- but the essential idea here is to
avoid all hassles with variable-length macro arguments by defining
XERROR as an object-like macro with no arguments at all.
-- Er*********@sun .com This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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
|
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?
|
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?
|
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
| |
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
|
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
|
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)?
|
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();
|
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;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |