0

Why this answer is 12? Can help me to explain it?

int sum (int i) {return ++i;} int main () { for(int = 0; i <=1; i++) {cout<<sum(i); }

19th Aug 2017, 5:21 PM
Halim Agung
Halim Agung - avatar
8 Respostas
+ 7
The answer isn't twelve really, but rather the for loop first outputs 1 and then outputs 2, and they are placed next to each other because there is no return ("\n" or endl) in the cout.
19th Aug 2017, 5:28 PM
ChaoticDawg
ChaoticDawg - avatar
+ 5
1st cycle: the return value is 1 (first i value is incremented then returned) 2nd cycle: like the first cycle 1 incremented to 2 and then returned to caller.
19th Aug 2017, 5:31 PM
Babak
Babak - avatar
+ 5
Yeah dear, you are right. Delete that.
19th Aug 2017, 5:49 PM
Babak
Babak - avatar
+ 3
If you were to change the for loop so that the conditional were i <= 2 instead, then the output would be 123. If you added << endl to the end of the cout so that it reads: cout << sum(i) << endl; the output will be 1 2 3 outputing the numbers all on different lines instead of next to each other on the same line.
19th Aug 2017, 5:38 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
@Babak no that will change the output entirely, because you are now incrementing the i in the for loop twice.
19th Aug 2017, 5:41 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
lul
19th Aug 2017, 6:34 PM
Петр
Петр - avatar
0
so if the code never use return on the main function, it will has 12 for the answer?
19th Aug 2017, 5:32 PM
Halim Agung
Halim Agung - avatar
0
thanks for the answer..finally i got it
19th Aug 2017, 6:58 PM
Halim Agung
Halim Agung - avatar