Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How does this code of c++ gives the output??

Status
Not open for further replies.

rahul.6sept

Full Member level 5
Joined
Nov 17, 2006
Messages
243
Helped
1
Reputation
2
Reaction score
1
Trophy points
1,298
Location
Guwahati, India
Activity points
2,889
Dear All,

the following code of c++ gives an output which I could not understand as how is this coming. Can someone help me understand it.

Code:
#include <iostream>
using namespace std;

#define MM_1(x,y) x*y
#define MM_2(x,y) (x*y)
#define MM_3(x,y) (x)*(y)

inline int MPLY (int x, int y){return x*y;}

int main(){
     int a=3,b=4;

     cout << "MM_1:" << MM_1(MM_1(a+1, b-1), a+b)<<endl;
     cout << "MM_2:" << MM_2(MM_2(a+1, b-1), a+b)<<endl;
     cout << "MM_3:" << MM_3(MM_3(a+1, b-1), a+b)<<endl;
     cout << "MPLY:" << MPLY(MPLY(a+1, b-1), a+b)<<endl;

     return 0;
}
I calculated for MM_1 the output to be 84 but the output it gives to be is only 8. How it is calculating it?

Regards
 
Last edited by a moderator:

hi Rahul, (Kaise ho?)

I am guessing that this Code's basic purpose is to highlight the same difference of results that you are getting. The reason of "8" in the result is the way C++ reads and performs its operations according to its precedence rules. You can read the CPP precedence rules on internet. Here is a link : "https://en.cppreference.com/w/cpp/language/operator_precedence"

Now, let me explain how it calculates 8 as the result:
for a=3, b=4

>> MM1(MM1(3+1,4-1),3+4)
>> MM1(3+1,4-1) * 3+4
>> 3+1*4-1*3+4
>> 3+4-3+4
>> 7-3+4
>>11-3
>>8

Hope it helps,
Regards,
 
Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top