Default Parameters


C++ has one more neat trick up it's sleeve for functions -- defining Default Parameters. What are they? Well, they're a way of saying what value should be passed to a function if you don't pass anything or have less arguments than are defined. Here's how you define a function to have default values in its argument list:

void salsa(int yum=2)

Note that you're setting the parameter yum to 2. What this is doing is defining a value, 2, that will be put into yum if you don't pass anything. So let's say we call salsa:

salsa();

Even though there was no argument passed, the function still works. Because no value was passsed, the variable yum is set to 2, and the function executes. If we wanted to pass a value, though, it would work just like functions always have. For instance,

salsa(231);

Would set yum, sure enough, to 231. Neat, huh? Now here's the tricky part. If you have a long list of parameters in a function, you have to put the ones with default values at the end. For instance,

void burrito(int taco, int nacho, int chimichanga=0, int beans=0)

is good, but

void burrito(int taco, int nacho=0, int chimichanga=0, int beans)

is bad, and won't work. Why not? Well imagine if you tried calling this function with 3 arguments. Did you want to send values for taco, nacho, and beans, or did you want to send values for taco,chimichanga, and beans? It gets much too confusing and could be interpreted many ways, so it's not allowed in C++.


Table of Contents

Procedures/Functions | Returning Values | Passing Variables | Using Functions
Function Overloading | Default Parameters | Exercises