Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
i have typed the following code but not able understand the output

#include<iostream.h>
#include<conio.h>
#define AREA(a) a*a;
int area(int a)
   {
   return a*a;
   }
void main()
   {
   cout<<AREA(5+2);
   cout<<"\t"<<area(5+2);
   }

</conio.h></iostream.h>

and the output is 17 and 49
im not able to understand why macro giving ans as 17 instead of 49
please solve this ques with your valueable comments

[edit]Code blocks added, formatting - OriginalGriff[/edit]
@griff
sir

why this code is replaced like this 5+2*5+2
can you please explain
Posted
Updated 20-Mar-11 6:15am
v3
Comments
Richard MacCutchan 20-Mar-11 16:32pm    
Unless you really know what you are doing then avoid macros like the plague. The side effects catch even the most experienced developers.

1 solution

It's pretty simple - operator precidence and preprocessors:
When you use area(5+2) the compiler does the math, and changes it to a call to area(7) - which returns 7*7 or 49.
When you use AREA(5+2) the preprocessor does a text subsitution, and replaces it with 5+2*5+2
Operator precidence of the "*" over the "+" then gets it compiled as 5 + (2*5) + 2 or 17.

To fix it, replace your definition by
C#
#define AREA(a) ((a)*(a))


[edit]Geoff Williams correctly pointed out that you need brackets round the whole macro definition to be truely safe, added with thanks. I spotted that you definitely don't need the semicolon on the end, removed with blushes... - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Geoff Williams 20-Mar-11 13:39pm    
To be really safe - or at least safe as you can be when using macros - you should wrap the macro definition in brackets as well i.e.

#define AREA(a) ((a) * (a))
OriginalGriff 20-Mar-11 16:26pm    
Good point! Next time I see one of your answers, I'll give you a five.
Corrected.
OriginalGriff 20-Mar-11 16:30pm    
I am really glad you pointed that out: I had also missed that it really, really, should not have had a semicolon on the end of the macro definition. :blush:
Sergey Alexandrovich Kryukov 20-Mar-11 15:21pm    
Correct, a 5.
Better yet, using preprocessor should be discouraged, especially in this case.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900