+ 1

Unexpected !.Why ?

#include<stdio.h> int main() { int a=1; printf(" %d %d %d \n",a,a++,++a); return 0; }

7th Oct 2017, 1:19 AM
Ishu Maurya
Ishu Maurya - avatar
13 ответов
+ 2
It starts by evaluating the last parameter of a function, then the second last and so on until the first. Example : int a = 5; printf("%d %d %d\n",a,++a,a++); -> printf(..., a, ++a, 5); // a == 6 printf(..., a, 7, 5); // a == 7 printf(..., 7, 7, 5);
9th Oct 2017, 6:08 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
I'm not sure it work exactly that wat @Baptiste, for your answer doesn't explain the output of the following code... Apparently the compiler evaluate the term "++a" prior the call of the function printf : #include<stdio.h> int main() { int a=1; printf(" %d %d %d \n",a,++a,a); return 0; }
9th Oct 2017, 8:45 PM
Corentin
Corentin - avatar
+ 1
finally u got the point man :)
8th Oct 2017, 3:22 PM
Ishu Maurya
Ishu Maurya - avatar
+ 1
The answer is simple : GCC evaluate function's parameters from right to left. I said GCC as it is SoloLearn's compiler and as this behavior is not defined in C norms. It is compiler dependant so you might have another behavior with mingw or clang for example @Infinity, cout can't be used as a test as it is different than printf, it is like you were doing : <<(<<(<<(cout, a++), a++) a); where you have to replace << by operator<< (Sorry, I was lazy :p)
9th Oct 2017, 5:11 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
nope
8th Oct 2017, 7:01 AM
Ishu Maurya
Ishu Maurya - avatar
0
absolutely correct @Infinity. Was a Mistake in the code which i've corrected right now. Have a Look at it and run the code again and tell why is it giving abnormal output
8th Oct 2017, 12:22 PM
Ishu Maurya
Ishu Maurya - avatar
0
i've corrected (edited) this code. look at the question again !
8th Oct 2017, 2:19 PM
Ishu Maurya
Ishu Maurya - avatar
0
i'd love to hear the reason why this happens.
8th Oct 2017, 4:28 PM
Ishu Maurya
Ishu Maurya - avatar
0
yeah bro ! the abnormal output ..m still finding the reason.
8th Oct 2017, 4:30 PM
Ishu Maurya
Ishu Maurya - avatar
0
@Prunier i am still not able to understand this fact... sorry m beginner. can u please explain it little further
9th Oct 2017, 5:24 AM
Ishu Maurya
Ishu Maurya - avatar
0
Of course ! But, which fact ? Being compiler dependent or the way GCC evaluate functions' parameters ?
9th Oct 2017, 5:29 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
the way GCC works
9th Oct 2017, 5:31 AM
Ishu Maurya
Ishu Maurya - avatar
0
Prior to it expression, but the expression is used as a parameter. Not prior to the line (which is different) So my explication is still correct ^^
9th Oct 2017, 9:26 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar