0

Please explain how the sum in the second expression is valid? Thanks

#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; }

3rd Dec 2016, 6:48 PM
Black Temple
Black Temple - avatar
4 ответов
+ 2
first call to sum returns 60 obviously in the second call since you're only passing in one argument, default value (42) will be used for second argument and it returns 66
3rd Dec 2016, 6:57 PM
HAL8999++;
HAL8999++; - avatar
+ 2
i understand but where is it stated that b is the default parameter?
12th Feb 2017, 2:22 PM
Black Temple
Black Temple - avatar
+ 1
sum() function is defined with a default parameter b=42. if you don't pass a second argument to the function 42 will be used.
3rd Dec 2016, 6:55 PM
Elio
Elio - avatar
0
//calling the function without b result = sum(x); cout << result << endl; here how does the compiler recognises - the first expression to be used for sum calculation, when it has not been mentioned in the second expression. like , sum(x) only states sum of x and nothing more.
3rd Dec 2016, 7:01 PM
Black Temple
Black Temple - avatar