+ 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?
6 odpowiedzi
+ 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;
☺
+ 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
+ 1
My Pleasure Kobby !! Happy That Your Doubt Has Been Cleared !!!
0
You Haven't Call The Function Above Properly ( With 2 Parameters ) ... Its Just A Function Prototype ... So The Output Is Only 66 ...
0
What if I need to use default value of first parameter and user defined parameter for second?
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