+ 1

Why the output in the function is "7 18 5"

#include <iostream> using namespace std; f1(Int &b,int c) {b++; return b+c;} Int main() {Int a=5; cout<<a<<" "<<f1(a,f1(a,a)<<" "<<a; return 0; }

18th Apr 2017, 8:23 AM
Nour Alnaser
Nour Alnaser - avatar
6 Respuestas
+ 5
First of all, a = 5 going to push into the stack. The inner function call first happens f(5, 5) which makes a = 6 then the outer function call from the previous result which was 6 + 5 = 11 happens and f(6, 11) is going to execute. Finally, after returning to main function, a = 7 and 7 + 11 = 18 now cout object take a look at the last stack value of 'a' variable returned by f function which is 7 then it evaluate the sequence of outputs. for example if you had count << a << " " << a << " " << a << " " << f(a, f(a,a)) << " " << a; All 'a' variables became 7, then latest function return value , that is,18, and after the nested function call, last stack's value pops and you just get the initial value of a, which was 5.
18th Apr 2017, 9:52 AM
Babak
Babak - avatar
+ 4
You are getting output 7 18 5, please go through following steps cout<<a<<" "<<f(a,f(a,a))<<" "<<a; will be evaluated as from right to left std::cout.operator<<(a).operator<<(f(a,f(a,a))).operator<<(a); 1. .operator<<(a) will returns 5 2. .operator<<(f(a,f(a,a))) f(a,a) f(5,5) a++= 6 step i 6 + 5 = 11 return statement f(a,f(a,a)) => f(6,11) a++= 7 step i 7 + 11 = 18 return statement returns 18 3. std::cout.operator<<(a) returns 7 (as it was incremented twice)
18th Apr 2017, 10:12 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 4
right most expression will evaluated first for example in expression c=a+b compiler will first evaluates a+b, then assigns the sum to the variable c.
18th Apr 2017, 10:32 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 4
@ Nour Compiler and language architectures are low level stuff and even though you know the language rules but sometimes their behaviour toward some sort of expressions makes you confuse. I suggest you to split it into 3 expression and see the result. cout << a << " "; cout << f(a, f(a, a)); cout << " " << a; http://stackoverflow.com/questions/7718508/order-of-evaluation-of-arguments-using-stdcout
18th Apr 2017, 10:41 AM
Babak
Babak - avatar
+ 1
I did not understand .. now the. compiler works from right to left or from left to right ????
18th Apr 2017, 10:23 AM
Nour Alnaser
Nour Alnaser - avatar
+ 1
Babak sheykhan ... I am sorry but I did not understand why it printed 5 though a=7
18th Apr 2017, 10:29 AM
Nour Alnaser
Nour Alnaser - avatar