+ 1

Hey friends please explain me this code and say why its output is ab?

#include <iostream> using namespace std; char Blackbox(char &ch){ int x=-1; if(x++>x) return ch++; else return ch--; } int main() { char ch1='b'; char ch2=Blackbox(ch1); cout<<ch1<<ch2; return 0; } // output is 'ab' ?

19th Sep 2018, 10:00 AM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
1 Antwort
+ 2
ok, couple of things to note here: 1) x++>x evaluates to false, because increment is done first, so both values are equal 2) return ch-- returns current ch, and AFTERWARDS ch gets decremented 3) char &ch means pass by reference, that's why ch1 is changed from b to a (decrement after return on ch1) 4) ch2 gets the returned value, which was b So the output is ab If you change ch-- to --ch, the output would be aa If you change x++>x to x+1>x , you will land in the first branch of if-else-statement. Same rules apply here, only with increment instead of decrement
19th Sep 2018, 11:19 AM
Matthias
Matthias - avatar