Why not just use local variables? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why not just use local variables?

I don't understand why you would give default values to a parameter variable. If the value does not have to be passed in the function call, why not just make it a local variable ?

16th Dec 2016, 5:42 PM
Kim McRae
2 Answers
+ 1
Because if you do not want the default value you can still pass in a different value. For example: int calcTicket( string movie, bool adult=true) { if(adult) //Calc normal price else //Give discount ..etc.. return price; } int main() { int t1 = calcTicket("The Revenant"); int t2 = calcTicket("Finding Nemo", false); If you made 'adult' a local variable, how would you do the above?
16th Dec 2016, 10:47 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
let me try to explain with an example: i've a class to open a file and write anything in it, and for testing purpose I set a default filename, like "test.txt", but if in the future i need to save it with a diferent name i just have to pass as a parameter, so my best way to explain the need for this feature is convenience and code reusability.
16th Dec 2016, 6:02 PM
Nilton Tadeu Ferreira Filho
Nilton Tadeu Ferreira Filho - avatar