Let's say I need to swap two int values frequently. I would write a macro:
#define swap(int a, int b) \
do { \
int temp = (a); \
(a) = (b); \
(b) = temp; \
} while (0)
Aside from the double evaluation of a and b, this works fine *except*
when either macro parameter a or b is called "temp." What's the best to
design macros to avoid these sort of collisions?
Is this a good candiate for using an identifier from that murky
legal-only-as-a-local-variable set, like _temp?
Thanks for your thoughts,
-Peter
(PS Yes, I know about various tricks with bitwise XOR, but I'm
interested in a general solution) 6 3943
In 'comp.lang.c', Peter Ammon <pe*********@ro cketmail.com> wrote: Let's say I need to swap two int values frequently. I would write a macro:
#define swap(int a, int b) \
Macro parameters have no type (or you mean 'inline').
Please don't retype, but copy and paste.
#define swap(a, b) \
do { \ int temp = (a); \
Hence, the macro name should be 'swap_int', or 'swap_i' or the like...
(a) = (b); \ (b) = temp; \ } while (0)
Aside from the double evaluation of a and b, this works fine *except* when either macro parameter a or b is called "temp." What's the best to design macros to avoid these sort of collisions?
Is this a good candiate for using an identifier from that murky legal-only-as-a-local-variable set, like _temp?
I'm not sure it's legal, hence I prefer to postfix with '_'
#define swap(a_, b_) \
do { \
int temp_ = (a_); \
etc.
A little ugly, I concede...
--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Emmanuel Delahaye wrote: In 'comp.lang.c', Peter Ammon <pe*********@ro cketmail.com> wrote:
Let's say I need to swap two int values frequently. I would write a macro:
#define swap(int a, int b) \
<snip> Hence, the macro name should be 'swap_int', or 'swap_i' or the like...
If you're going to do that it's presumably because you have different
types you need to swap so you could just pass in the type as an argument
to one macro instead of creating several similair macros, e.g.:
#define swap(type,a,b) \
do { \
type _temp; \
...
<snip>Is this a good candiate for using an identifier from that murky legal-only-as-a-local-variable set, like _temp?
Yes. I'm not sure it's legal, hence I prefer to postfix with '_'
#define swap(a_, b_) \ do { \ int temp_ = (a_); \ etc.
A little ugly, I concede...
No need for the underscores on the parameters.
Ed.
Emmanuel Delahaye wrote: In 'comp.lang.c', Peter Ammon <pe*********@ro cketmail.com> wrote:
Let's say I need to swap two int values frequently. I would write a macro:
#define swap(int a, int b) \
Macro parameters have no type (or you mean 'inline').
Oops :)
Please don't retype, but copy and paste.
The code isn't actually C, but the general problem is. But since you
asked...
#define ASSIGN(a, b) do { id _temp = (a); (a)=[(b) retain]; [_temp
release]; } while (0)
#define ASSIGN_COPY(a, b) do { id _temp = (a); (a) = [(b) copy]; [_temp
release]; } while (0) #define swap(a, b) \
do { \ int temp = (a); \
Hence, the macro name should be 'swap_int', or 'swap_i' or the like...
(a) = (b); \ (b) = temp; \ } while (0)
Aside from the double evaluation of a and b, this works fine *except* when either macro parameter a or b is called "temp." What's the best to design macros to avoid these sort of collisions?
Is this a good candiate for using an identifier from that murky legal-only-as-a-local-variable set, like _temp?
I'm not sure it's legal, hence I prefer to postfix with '_'
#define swap(a_, b_) \ do { \ int temp_ = (a_); \ etc.
A little ugly, I concede...
--
Pull out a splinter to reply.
Groovy hepcat Peter Ammon was jivin' on Fri, 21 May 2004 11:54:41
-0700 in comp.lang.c.
Avoiding name collisions in macros's a cool scene! Dig it! Let's say I need to swap two int values frequently. I would write a macro:
#define swap(int a, int b) \ do { \ int temp = (a); \ (a) = (b); \ (b) = temp; \ } while (0)
Aside from the double evaluation of a and b, this works fine *except* when either macro parameter a or b is called "temp." What's the best to design macros to avoid these sort of collisions?
Try creating some kind of Frankenstein's monster thingie with token
concatenation, maybe. Concatenate the names of the two macro arguments
together (and append or prepend temp or something to avoid the
resulting token being a keyword or something) and use the resulting
token as the variable's identifier. For example:
#include <stdio.h>
#define PASTE_(a, b) a ## b
#define PASTE(a, b) PASTE_(a, b)
#define SWAP(t, a, b) do{t PASTE(PASTE(a, b), temp) = (a); \
(a) = (b); \
(b) = PASTE(PASTE(a, b), temp);}while(0)
int main(void)
{
int x = 1, y = 9;
printf("x = %d, y = %d\n", x, y);
SWAP(int, x, y);
printf("x = %d, y = %d\n", x, y);
return 0;
}
--
Dig the even newer still, yet more improved, sig! http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"? ph******@alphal ink.com.au.NO.S PAM (Peter "Shaggy" Haywood) writes: Groovy hepcat Peter Ammon was jivin' on Fri, 21 May 2004 11:54:41 -0700 in comp.lang.c. Avoiding name collisions in macros's a cool scene! Dig it!
Let's say I need to swap two int values frequently. I would write a macro:
#define swap(int a, int b) \ do { \ int temp = (a); \ (a) = (b); \ (b) = temp; \ } while (0)
Aside from the double evaluation of a and b, this works fine *except* when either macro parameter a or b is called "temp." What's the best to design macros to avoid these sort of collisions?
Try creating some kind of Frankenstein's monster thingie with token concatenation, maybe. Concatenate the names of the two macro arguments together (and append or prepend temp or something to avoid the resulting token being a keyword or something) and use the resulting token as the variable's identifier. For example:
#include <stdio.h>
#define PASTE_(a, b) a ## b #define PASTE(a, b) PASTE_(a, b) #define SWAP(t, a, b) do{t PASTE(PASTE(a, b), temp) = (a); \ (a) = (b); \ (b) = PASTE(PASTE(a, b), temp);}while(0)
int main(void) { int x = 1, y = 9;
printf("x = %d, y = %d\n", x, y); SWAP(int, x, y); printf("x = %d, y = %d\n", x, y);
return 0; }
This technique only works if the second and third macro arguments are
identifiers. Otherwise, the pasting doesn't yield a valid preprocessor
token, e.g.
int a [] = {1, 9};
SWAP (int, a [0], a [1]);
doesn't work.
It also "pollutes" the namespace with `PASTE' and `PASTE_'. If that is
acceptable, why not go for the following much simpler solution:
#define SWAP(t, a, b) do { t PASTE = (a); \
(a) = (b); \
(b) = PASTE; } while (0)
Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
In article <news:cu******* ******@zero-based.org>
Martin Dickopp <ex************ ****@zero-based.org> writes: [The token-pasting] technique [using the names of the variables to be swapped] only works if the second and third macro arguments are identifiers. Otherwise, the pasting doesn't yield a valid preprocessor token, e.g.
int a [] = {1, 9}; SWAP (int, a [0], a [1]);
doesn't work.
Indeed.
It also "pollutes" the namespace with `PASTE' and `PASTE_'. If that is acceptable, why not go for the following much simpler solution:
#define SWAP(t, a, b) do { t PASTE = (a); \ (a) = (b); \ (b) = PASTE; } while (0)
My usual method is just to write such swaps in-line, e.g., when
expanding a specialized sort function in C (in C++ one would just
use templates; and in Ada one would use generics, and so on; in
these languages the problem has a "language-preferred" solution).
If for some reason a swap macro appeals, one could perhaps do away
with the "type" parameter entirely, and supply instead a "temporary
variable" parameter:
#define SWAP(t, a, b) (t = (a), (a) = (b), (b) = t)
...
int a[N];
int swaptmp;
...
SWAP(swaptmp, a[i], a[j]); /* cf. SWAP(int, a[i], a[j]) */
In this version of the macro, I deliberately did not parenthesize
occurrences of the name "t" because it is supposed to be a simple
variable of the appropriate type.
If one wishes to reduce the scope of the variable to just the braces
introduced by a do-while(0) (e.g., to assist a compiler in
optimization) there is another variant of this method:
#define SWAP(t, v, a, b) \
do { t v = (a); (a) = (b); (b) = v; } while (0)
...
SWAP(int, swaptmp, a[i], a[j]);
So far, however, it has been my experience that compilers smart
enough to optimize swaps into machine-level XCHG instructions (or
equivalent) are also smart enough to do dataflow and lifetime
analysis on variables, so that they can already determine that
the "swaptmp" variable's value persists only for the one source
line.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: hasadh |
last post by:
Hello,
probably this may be a simple qn to u all but I need an answer plz.
In my software i used macros like OK,TRUE,FALSE,FAILURE . A friend who
included this code as a library into his module said that in his code
he couldnt use the above words as function names or variable names and
got compilation errors. He advised me to use them as enums instead of
macros. is he right ???
(in my code the macros are used as return values from fns...
|
by: Sweety |
last post by:
plz reply,
thanks in advance.
bye
|
by: Walid |
last post by:
Hey,
I was trying some code with the .Net framework 1.1, and I found that the
Interface name collisions is still not resolved in that version of the .net
framework.
I am refering to that piece of code which i took from the book of Inside C#
(Archer).
using System;
|
by: sounak |
last post by:
How could we get a macro name from a macro value
such that
in a header file
#define a 100
#define b 200
now the source file will be such that
the user gives 100
then the value is outputted as a
the user gives 200
then the value is outputted as b
|
by: Scott McFadden |
last post by:
C++ has some nice macros for obtaining the current function name, current
source file, and current line number (__FUNCTION__, __FILE__, __LINE__).
Does C# have any comparable MACROS?
| |
by: Cephalobus_alienus |
last post by:
Hello,
I know that macros are evil, but I recently came across a problem
that I couldn't figure out how to solve with templates.
I wanted to create a set of singleton event objects, and wrote the
following macro:
#define GET_SINGLETON_EVENT_FUNCTION(FUNCTION_NAME,MANUAL_RESET,\
INITIAL_STATE,EVENT_NAME) \
|
by: Zytan |
last post by:
Shot in the dark, since I know C# doesn't have macros, and thus can't
have a stringizer operator, but I know that you can get the name of
enums as strings, so maybe you can do the same with an ordinary
variable (like an int) somehow. Is it possible? int.ToString()
returns the value of the int as a string, not the name, so I am
thinking 'no'.
Zytan
|
by: Tyno Gendo |
last post by:
I'm writing a test "modular site". So far I have created an App class,
a Module Manager class and a couple of test modules.
The Manager looks in a directory called 'modules' and then for every
..php file is try to create a class of type <filenameminus the .php, so
eg. for testmodule.php it tries to create a class "testmodule" and puts
it into an array within the module manager called $_modules
Module Manager has a dispatch_message...
|
by: Markus Dehmann |
last post by:
Do I have to handle hash collisions in a hash_set myself?
I did a test in which I use find() to look for objects in a hash_set.
These objects are definitely not contained, but find() sometimes finds
them anyway. See this code:
<code>
#include <iostream>
#include <stdexcept>
#include <ctime>
|
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: 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,...
| |
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...
|
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: 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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |