+ 3

A small question about CPP

https://code.sololearn.com/c77aqVQCFsAA/?ref=app #include <iostream> #define M(a) ((a)*(a)) using namespace std; int main() { int i,j; for (i=1,j=1;i<=5;i++) cout<<M(j++)<<endl; return 0; } How the define work in this code piece? why the answer which provided by the text book turned to be 1 9 25 49 81 ? But why the process got the results below? 2 12 30 56 90 Thanks alot ( ´▽` )

4th Mar 2019, 12:21 AM
LapterGrsd
LapterGrsd - avatar
7 odpowiedzi
+ 6
Yeah, I forgotton to mention as well: https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points Multiple prefix/postfix operators used between two sequence points will cause undefined behavior in older compilers, so the result of: j++*j++ in itself is compiler dependent. It's not surprising to get results which differ compared to your textbook.
4th Mar 2019, 2:01 AM
Fermi
Fermi - avatar
+ 3
Macros are ways the preprocessor substitute an identifier with another piece of identifier in a code before compilation. #define M(a) ((a)*(a)) With the above #define directive, whatever is being passed into M(a) as a, will be translated to ((a)*(a)) in its literal sense. Hence, passing j++ means that the resulting code of M(j++) will turn out to be ((j++)*(j++)) As a result, j is incremented twice per loop iteration.
4th Mar 2019, 12:39 AM
Fermi
Fermi - avatar
+ 3
Let's understand: Давайте разбираться: 1. #include <iostream> 2. #define M(a) a*a 3. using namespace std; 4. 5. int main() { 6. int i, j; 7. for (i=1, j=1; i<=5; i++) 8. cout<<M(j++)<<endl; 9. return 0; 10. } Macro M(j++) = M(a) a*a replaces M(a) => => M(j++) = (j++)*(j++) => As a result, we have: В результате чего мы имеем: Old compiler: Старый компилятор: 1) (j=1) * j => cout<<"1" => j=1+1; 2) (j=2+1)*j => cout<<"9" => j=3+1; 3) (j=4+1)*j => cout<<"25" => j=5+1; 4) (j=6+1)*j => cout<<"49" => j=7+1; 5) (j=8+1)*j => cout<<"81" => j=9+1; New compiler: Новый компилятор: 1) (j=1) * (j=1+1) => cout<<"2"; 2) (j=2+1) * (j=3+1) => cout<<"12"; 3) (j=4+1) * (j=5+1) => cout<<"30"; 4) (j=6+1) * (j=7+1) => cout<<"56"; 5) (j=8+1) * (j=9+1) => cout<<"90"; https://code.sololearn.com/c365ec61RTu0/?ref=app
4th Mar 2019, 1:47 AM
Solo
Solo - avatar
+ 3
I had no idea this was compiler dependent.
5th Mar 2019, 1:42 PM
Sonic
Sonic - avatar
+ 1
Fermi Thanks alot! The compiler which used in the text book was too old!
4th Mar 2019, 2:36 AM
LapterGrsd
LapterGrsd - avatar
0
Kiran Bodipati Thanks! I get it
7th Mar 2019, 3:59 AM
LapterGrsd
LapterGrsd - avatar