functions default arguments | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

functions default arguments

#include <iostream> using namespace std; int volume(int l=1, int w=1, int h=1) { return l*w*h; } int main() { cout << volume() << endl; cout << volume(5) << endl; cout << volume(2, 3) << endl; cout << volume(3, 7, 6) << endl; } help me understand this code like when we have volume(5) then how the formula works???

21st Jul 2019, 8:08 AM
Syed Shahrose
Syed Shahrose - avatar
2 Answers
+ 2
Default arguments work like this: if the argument isn't specified, it will be the default parameter. So volume() is 1 * 1 * 1, volume(5) is 5 * 1 * 1, and so on. Please, if you are trying to get a good answer, include relevant tags, I don't think "leaners" is that important. Also, this question isn't that important to ask it twice in a row, mind deleting the first one? ¯\_(ツ)_/¯
21st Jul 2019, 8:12 AM
Airree
Airree - avatar
0
Imagine the parameter of a function as a box. def f(x): # function does stuff using x When you call the function, you fill a value into that box. f(5) # so function does # the stuff it does using 5 A default argument just puts something in the box to begin with. def f(x=42): # stuff with x Now you can call the function with or without argument. f(5) # function uses 5 f() # function uses what's in # the box per default (so 42) Sorry, I explained it with python, but the idea is the same in C++.
21st Jul 2019, 10:17 AM
HonFu
HonFu - avatar