473,805 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

variadic arithmetic, boolean operators

(Note: C99 supports variadic macros, but C89 does not.)

I'm pretty sure what I'm trying to do is impossible, but I'll ask here
in case I'm missing something.

I'm trying to define generic, variadic arithmetic and boolean operators.
For example,

product (2, sum (3, 4), 5);

should expand to

(2) * ((3) + (4)) * (5);

Here is my pseudocode:

#define sum(x,y) \
(x) + (y)

#define sum(x, y, ...) \
(x) + sum (y, __VA_ARGS__)

int main (void)
{
sum (1, 2, 3, 4);
return 0;
}

Unfortunately, this has two problems:

- Macros cannot be overriden, hence the base case cannot be caught
generically. (You can define the base case as a function if the
definition (and declaration) precede the macro definition.)

- Macros expansion is not recursive (apparently).

For example, GCC's preprocessor outputs the following:

tmp.c:4:1: warning: "sum" redefined
tmp.c:1:1: warning: this is the location of the previous definition
# 1 "tmp.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "tmp.c"


int main (void)
{
(1) + sum (2, 3, 4);
return 0;
}

Can someone please either confirm that this is impossible in C, or
suggest how to go about it?

--
-trent
Physics is what results when you pollute mathematics with reality.
Nov 14 '05 #1
3 2044
Trent Buck wrote:
(Note: C99 supports variadic macros, but C89 does not.)

I'm pretty sure what I'm trying to do is impossible, but I'll ask here
in case I'm missing something.

I'm trying to define generic, variadic arithmetic and boolean operators.
For example,

product (2, sum (3, 4), 5);

should expand to

(2) * ((3) + (4)) * (5);

Here is my pseudocode:

#define sum(x,y) \
(x) + (y)

#define sum(x, y, ...) \
(x) + sum (y, __VA_ARGS__)

int main (void)
{
sum (1, 2, 3, 4);
return 0;
}

Unfortunately, this has two problems:

- Macros cannot be overriden, hence the base case cannot be caught
generically. (You can define the base case as a function if the
definition (and declaration) precede the macro definition.)

- Macros expansion is not recursive (apparently).


My suggestion is to change your design so that you are passing
containers (lists, vectors, arrays, etc.) to each function. Each
function would return the result. This design would eliminate
the need for variable argument lists.

int sum(int * array_of_intege rs,
unsigned int num_integers)
{
int result;
unsigned int index;
for (index = 0, result = 0;
index < num_integers;
++index)
{
result += *array_of_integ ers++;
}
return result;
}
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 14 '05 #2
Up spake Thomas Matthews:
My suggestion is to change your design so that you are passing
containers (lists, vectors, arrays, etc.) to each function. Each
function would return the result. This design would eliminate
the need for variable argument lists.


Not a solution I'm particularly taken with, but better than anything I
had come up with. Thank you.

--
-trent
Turn off your targeting computer, Luke. ASS. AHS. You have a better
chance of making this shot by guessing.
Nov 14 '05 #3
If using gcc, I might say use the ({}) extension:

#define sum(s...) \
({ int args[] = { s }; \
mysum(args, sizeof(args)/sizeof(*args)); \
})

int mysum(int args[], int n)
{
int i,w=0;

for(i=0;i<n;i++ ) w+= args[i];
return w;
};
For C99, perhaps a make_list macro could be a useful
approach... so you would have

make_list(list, 3,4,5,6)
sum(list);

struct List {
int *arr;
int len;
};

#define make_list(L,... ) \
do {
int args[] = { __VA_ARGS__ };
int len = sizeof(args) / sizeof(*args);
L.args = args;
L.len = len;
} while(0)
-Jmh

Nov 14 '05 #4

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

Similar topics

14
2534
by: greg | last post by:
Discussion is invited on the following proto-PEP. ------------------------------------------------------------- PEP ??? - Overloadable Boolean Operators ======================================== SUMMARY This PEP proposes an extension to permit objects to define their own
5
2850
by: Lionel B | last post by:
Greetings, I am trying to implement "element-wise" arithmetic operators for a class along the following lines (this is a simplified example): // ----- BEGIN CODE ----- struct X { int a,b;
19
4268
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
43
26545
by: Mehta Shailendrakumar | last post by:
Hello, Can anyone suggest me operator to perform arithmetic shift in C? May it be for a perticular compiler. Thank you in advance. Regards, Shailendra
12
2123
by: Raghu | last post by:
Hello all, I need your help on how to redefine teh function of arithmetic operators in C. for example : if there is an equation c = a/b; i want to execute my own algorithm for division operator. I am compelled to use the native C , instead of calling functions or using macros for doing arithmetic operations.
2
2094
by: pinkfloydhomer | last post by:
Can I use printf inside a variadic function that I am writing? Like: void print(const char * format,...) { va_list va; va_start(va, format); char buffer; // yeah, I know... vsprintf(buffer, format, va);
335
11896
by: extrudedaluminiu | last post by:
Hi, Is there any group in the manner of the C++ Boost group that works on the evolution of the C language? Or is there any group that performs an equivalent function? Thanks, -vs
16
3256
by: Shawnk | last post by:
I would like to perform various boolean operations on bitmapped (FlagsAttribute) enum types for a state machine design as in; ------------------- enum portState { Unknown, Open,
33
2573
by: Stef Mientki | last post by:
hello, I discovered that boolean evaluation in Python is done "fast" (as soon as the condition is ok, the rest of the expression is ignored). Is this standard behavior or is there a compiler switch to turn it on/off ? thanks, Stef Mientki
0
9596
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
10607
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
10359
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10364
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,...
0
9182
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
5541
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
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4317
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
3
3007
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.