473,385 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Macro al posto di una funzione

Ciao a tutti,

in alcuni casi le funzioni in C sono così semplici che è meglio
definirle come delle macro. Per evitare che l'utilizzatore si
accorga di usare una macro o una funzione, avevo pensato di
scrivere la macro in questo modo:

#define mul(x,y) {x*y;}

In questo modo, chiunque utilizzi la mia macro potrà scrivere
semplicemente:
mul(x,y);
come se fosse una semplice funzione.
Però, se devo scrivere:
if( x>0 )
mul(x,y);
else
mul(-x,y);
....il compilatore mi dà giustamente errore. Il problema di sintassi
si risolve mettendo le parentesi graffe ai due rami dell'if, ma
normalmente queste non sono obbligatorie.

Esiste un modo più elegante per fare quello che voglio?
Nov 14 '05 #1
10 2050
"pozz" <pN************@libero.it> ha scritto nel messaggio
news:8i**********************@twister2.libero.it.. .
Ciao a tutti,


Oooops, I believed posting in an italian group, excuse me.

My question is:
when I define a function as a macro I use:
#define mul(x,y) {x*y;}
So the programmer can use the macro as it was a function, such as:
mul(x,y);

But, when there is an "if" statement as in:
if( x>0 )
mux(x,y);
else
mux(-x,y);
the compiler exits with error. It's right and I resolve the problem
using {} in the "if" branches. Is there an elegant way to define a
function as a macro without problems in "if" statement?
Nov 14 '05 #2
pozz <pN************@libero.it> scribbled the following:
Ciao a tutti, in alcuni casi le funzioni in C sono così semplici che è meglio
definirle come delle macro. Per evitare che l'utilizzatore si
accorga di usare una macro o una funzione, avevo pensato di
scrivere la macro in questo modo: #define mul(x,y) {x*y;} In questo modo, chiunque utilizzi la mia macro potrà scrivere
semplicemente:
mul(x,y);
come se fosse una semplice funzione.
Però, se devo scrivere:
if( x>0 )
mul(x,y);
else
mul(-x,y);
...il compilatore mi dà giustamente errore. Il problema di sintassi
si risolve mettendo le parentesi graffe ai due rami dell'if, ma
normalmente queste non sono obbligatorie. Esiste un modo più elegante per fare quello che voglio?


In vostro programmo, il preprocessor transforma il texto por questo:

if( x>0 )
{x*y;};
else
{-x*y;};

Questo e un error, que il "else" non ha un "if" por attachi in.

Scriver vostro macro como questo:

#define mul(x,y) ((x)*(y))

e vostro programmo functionera.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"There's no business like slow business."
- Tailgunner
Nov 14 '05 #3
pozz wrote:

My question is:
when I define a function as a macro I use:
#define mul(x,y) {x*y;}
So the programmer can use the macro as it was a function, such as:
mul(x,y);

But, when there is an "if" statement as in:
if( x>0 )
mux(x,y);
else
mux(-x,y);
the compiler exits with error. It's right and I resolve the problem
using {} in the "if" branches. Is there an elegant way to define a
function as a macro without problems in "if" statement?


Try (only parentheses, no braces):

#define mul(x, y) ((x) * (y))

Then you can safely write:

if (x >= 0) z = mul( x, y);
else z = mul(-x, y);

--
fix (vb.): 1. to paper over, obscure, hide from public view; 2.
to work around, in a way that produces unintended consequences
that are worse than the original problem. Usage: "Windows ME
fixes many of the shortcomings of Windows 98 SE". - Hutchison

Nov 14 '05 #4
CBFalconer <cb********@yahoo.com> wrote:
pozz wrote:

My question is:
when I define a function as a macro I use:
#define mul(x,y) {x*y;}
BTW, it is good practice to give macros all-capital names, so they can
be distinguished from real functions; this is important, because some
macros can evaluate their arguments more than once. For example,

#define DOUBLE(x) ((x)+(x))
int double(int x)
{
return x+x;
}
int a,b;

a=DOUBLE(4); /* a is 8; valid. */
a=double(4); /* Ditto. */
b=double(a++); /* b is 16; a is now 9. Also valid. */
b=DOUBLE(a++); /* Oops... */

The final line is not OK, because it is preprocessed to

b=((a++)+(a++));

which modifies a twice between sequence points, giving undefined
behaviour. Thus, you can pass arguments with side effects to functions,
but you're not guaranteed that you can do so to macros. Hence the
importance of knowing which function-like calls are macros.
But, when there is an "if" statement as in:
if( x>0 )
mux(x,y);
else
mux(-x,y);
the compiler exits with error.
Try (only parentheses, no braces):

#define mul(x, y) ((x) * (y))


And when your macro gets too complicated for that, try
<http://www.eskimo.com/~scs/C-faq/q10.4.html>.

Richard
Nov 14 '05 #5
On Thu, 06 May 2004 07:13:18 GMT, in comp.lang.c ,
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote:
CBFalconer <cb********@yahoo.com> wrote:
pozz wrote:
>
> My question is:
> when I define a function as a macro I use:
> #define mul(x,y) {x*y;}


BTW, it is good practice to give macros all-capital names, so they can
be distinguished from real functions; this is important, because some
macros can evaluate their arguments more than once.


Its also a good idea to use extra parens, for simlar reasons.
For example consider what
mul(4+5, 5);
evaluates to.

I'm also slightly puzzled at your macro. Its not strictly a function-like
macro since it doesn't return a value. You also can't use it in an
assignment.
This oddity by the way is probably causing your error. If you expand out
your macro when used in the if() statement, you'll see that.
The way to define function-like macros is
#define MUL(a,b) ((a) * (b))
You can then use MUL as a true function.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #6
Mark McIntyre wrote:

On Thu, 06 May 2004 07:13:18 GMT, in comp.lang.c ,
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote:
CBFalconer <cb********@yahoo.com> wrote:
pozz wrote:
>
> My question is:
> when I define a function as a macro I use:
> #define mul(x,y) {x*y;}


BTW, it is good practice to give macros all-capital names, so they can
be distinguished from real functions; this is important, because some
macros can evaluate their arguments more than once.


Its also a good idea to use extra parens, for simlar reasons.
For example consider what
mul(4+5, 5);
evaluates to.

I'm also slightly puzzled at your macro. Its not strictly a function-like
macro since it doesn't return a value. You also can't use it in an
assignment.
This oddity by the way is probably causing your error. If you expand out
your macro when used in the if() statement, you'll see that.
The way to define function-like macros is
#define MUL(a,b) ((a) * (b))
You can then use MUL as a true function.


Mark, there is nothing there that I wrote. Please edit the
attributes to match the portion quoted after snipping. I have
left your entire article unsnipped to illustrate the point.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #7
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> ha scritto nel messaggio
news:40****************@news.individual.net...
CBFalconer <cb********@yahoo.com> wrote:
pozz wrote:
But, when there is an "if" statement as in:
if( x>0 )
mux(x,y);
else
mux(-x,y);
the compiler exits with error.

Try (only parentheses, no braces):

#define mul(x, y) ((x) * (y))


Ok, and what if I want to include more C-instructions in a single macro?
For example:
#define FOO(x,y) (x++;y*=2;)

That's an error, so I can write:
#define FOO(x,y) x++;y*=2;
But if I write:
while( x<100 )
FOO(x,y);
the program is different than what it should be. The y*=2; instruction
will be executed only once after exiting from while() but I want to
execute it inside the while().

Nov 14 '05 #8
pozz wrote:

Ok, and what if I want to include more C-instructions in a single macro?
[...]


This is Question 10.4 in the comp.lang.c Frequently
Asked Questions (FAQ) list

<http://www.eskimo.com/~scs/C-faq/top.html>

--
Er*********@sun.com
Nov 14 '05 #9
On Thu, 06 May 2004 23:42:50 GMT, in comp.lang.c , CBFalconer
<cb********@yahoo.com> wrote:
Mark McIntyre wrote:

On Thu, 06 May 2004 07:13:18 GMT, in comp.lang.c ,
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote:
>CBFalconer <cb********@yahoo.com> wrote:
>
>> pozz wrote:
>> >
>> > My question is:
>> > when I define a function as a macro I use:
>> > #define mul(x,y) {x*y;}
>
>BTW, it is good practice to give macros all-capital names, so they can
>be distinguished from real functions; this is important, because some
>macros can evaluate their arguments more than once.


Its also a good idea to use extra parens, for simlar reasons.
For example consider what
mul(4+5, 5);
evaluates to.

I'm also slightly puzzled at your macro. Its not strictly a function-like
macro since it doesn't return a value. You also can't use it in an
assignment.
This oddity by the way is probably causing your error. If you expand out
your macro when used in the if() statement, you'll see that.
The way to define function-like macros is
#define MUL(a,b) ((a) * (b))
You can then use MUL as a true function.


Mark, there is nothing there that I wrote. Please edit the
attributes to match the portion quoted after snipping. I have
left your entire article unsnipped to illustrate the point.


Chuck, apologies if this sounds rude, but I'm not going to trawl through
all the attributions of every post I reply to, just to make sure some
remark by some attribution line remains in. I'm happy to make reasonable
efforts, of course.
In this case it seems (to me) that Richard snipped what you said.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #10
Mark McIntyre <ma**********@spamcop.net> wrote:
On Thu, 06 May 2004 23:42:50 GMT, in comp.lang.c , CBFalconer
<cb********@yahoo.com> wrote:
Mark, there is nothing there that I wrote. Please edit the
attributes to match the portion quoted after snipping. I have
left your entire article unsnipped to illustrate the point.


Chuck, apologies if this sounds rude, but I'm not going to trawl through
all the attributions of every post I reply to, just to make sure some
remark by some attribution line remains in. I'm happy to make reasonable
efforts, of course.
In this case it seems (to me) that Richard snipped what you said.


Erm... no. Only in the bit you quoted; not in the entire post.

Richard
Nov 14 '05 #11

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

Similar topics

25
by: Andrew Dalke | last post by:
Here's a proposed Q&A for the FAQ based on a couple recent threads. Appropriate comments appreciated X.Y: Why doesn't Python have macros like in Lisp or Scheme? Before answering that, a...
699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
3
by: John | last post by:
Please, consider this macro: #define mymacro(arg1, arg2) arg1 and arg2 Then it is used: mymacro(boys, girls) How is its expansion?
2
by: Pete | last post by:
In Access 95/97 I used to be able to create pull down menus (File,Edit ...) from a macro. It seems there used to be some wizard for that. However in Access 2000 it seems you have to build your...
7
by: Newbie_sw2003 | last post by:
Where should I use them? I am giving you my understandings. Please correct me if I am wrong: MACRO: e.g.:#define ref-name 99 The code is substituted by the MACRO ref-name. So no overhead....
1
by: Michele | last post by:
Ho una funzione definita così: #define CEIL(num,den) ( ((num)+(den)-1)/(den) ) e l'uso è questo; int len; len = CEIL(L, step); la CEIL però difficilmente mi restituisce un numero intero...
3
by: Alexander Ulyanov | last post by:
Hi all. Is it possible to pass the whole blocks of code (possibly including " and ,) as macro parameters? I want to do something like: MACRO(FOO, "Foo", "return "Foobar";", "foo();...
5
by: Bill | last post by:
This database has no forms. I am viewing an Access table in datasheet view. I'd like to execute a macro to execute a function (using "runcode"). In the function, I'll reading data from the record...
1
by: michele.binetti | last post by:
Ciao a tutti, accedendo, per la prima volta, ad una pagina contenuta in un iframe non ho problemi. se riaccedo alla stessa, per la seconda volta, Internet Explorer mi da questa segnalazione:...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.