#define

M

Meenu

the value of a is 11, how??

#define SQR(x) (x*x)
int main()
{
int a,b=3;
a=SQR(b+2);
printf("a=%d\n",a);
return 0;
}
 
J

jacob navia

Meenu a écrit :
the value of a is 11, how??

#define SQR(x) (x*x)
int main()
{
int a,b=3;
a=SQR(b+2);
printf("a=%d\n",a);
return 0;
}
a = SQR(b+2) where SQR --> "b+2"
a = b+2*b+2
a = 3+(2*3)+2
a = 3+6+2
a = 11
 
M

Martin Ambuhl

Meenu said:
the value of a is 11, how??

#define SQR(x) (x*x)
int main()
{
int a,b=3;
a=SQR(b+2);

is
a=b+2*b+2;
since the value of b is 3, the value of the expansion is
a=3+6+2;
= 11;
This is why, if you are _sure_ that there are no side effects in the
arguments to SQR() it should be
#define SQR(x) ((x)*(x))
But, of course, you have no such guarantees about no side effects. Both
versions die with
SQR(++b);
for example.
So, what you really want is
inline int square_int(int x) { return x*x; }
 
A

abhik

hi meenu ,

see the problem here is that all the #defines are taken care at
preprocessing level .
So wat the compiler gets is not 5*5 but actually 3 + 2 * 3 + 2
which is 11
 
G

Giorgos Keramidas

abhik said:
see the problem here is that all the #defines are taken care at
preprocessing level .
So wat the compiler gets is not 5*5 but actually 3 + 2 * 3 + 2
which is 11

Which can easily be solved by proper use of parentheses:

#define SQR(x) ((x) * (x))

This macro has yet another potential "bug", which is caused by using the
macro argument twice. If the "x" expression has side-effects they will
be doubled, yielding strange results in invocations like:

SQR(b++, b++)

But that's probably not what the original poster asked for :)
 
P

Peter Pichler

Giorgos said:
#define SQR(x) ((x) * (x))

This macro has yet another potential "bug", which is caused by using the
macro argument twice. If the "x" expression has side-effects they will
be doubled, yielding strange results in invocations like:

SQR(b++, b++)

....which would most likely not compile :)

(SQR takes ONE parameter)

Peter
 
A

akarl

Peter said:
...which would most likely not compile :)

(SQR takes ONE parameter)

Moreover, even if the function *did* take two parameters it would cause
problems (undefined behavior) even if it was a "true" function
(modification of a variable twice with no intervening sequence point).

August
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top