+ 1

#include <iostream> using namespace std; int sum(int a, int b=42) { int result = a + b; return (result); } int main() { int x = 24; int y = 36; //calling the function with both parameters int result = sum(x, y); cout << result << endl; //calling the function without b result = sum(x); cout << result << endl; return 0; } why is da last function cout 66 and not 48 isn't it suppose to add 24+24?

26th Aug 2016, 10:49 AM
Emmanuel Opare Adjei
Emmanuel Opare Adjei - avatar
6 ответов
+ 7
I'm not sure where you are getting 24 + 24 from, but when you called the function the second time to passed in 'x' (24), which means you are setting 'a' in the function to 24. Because you didn't pass a second value, 'b' is going to use its default value of 42, so the function returns 24 + 42, which is 66. By the way, instead of creating a whole new variable in the function, you could always just return a + b; ☺
26th Aug 2016, 11:50 AM
Cohen Creber
Cohen Creber - avatar
+ 1
i get it now, the 1st function assigns the answer 42 to result and the last adds 24 to it and couts the answer thanks Shashank Pai
26th Aug 2016, 11:11 AM
Emmanuel Opare Adjei
Emmanuel Opare Adjei - avatar
+ 1
My Pleasure Kobby !! Happy That Your Doubt Has Been Cleared !!!
26th Aug 2016, 3:28 PM
Shashank Pai
Shashank Pai - avatar
0
You Haven't Call The Function Above Properly ( With 2 Parameters ) ... Its Just A Function Prototype ... So The Output Is Only 66 ...
26th Aug 2016, 10:53 AM
Shashank Pai
Shashank Pai - avatar
0
What if I need to use default value of first parameter and user defined parameter for second?
30th Sep 2016, 7:20 PM
Anurag Sharma
Anurag Sharma - avatar
0
The answer is 66 because the value for second int has not been specified in main function , so the value for the second int is being taken from the function defined earlier i.e. The default value 42. Hope that helps, Mukul
16th Oct 2016, 2:17 PM
mukul