9.8 Functions and Default Arguments

9.8 Functions and Default Arguments

Consider the following scenario in which we want to use a function to play a beep through the computer's speakers. Most of the time, the programmer will want the volume to be played at the maximum volume (100), but 10% of the time it might be played at a different volume. The declaration for the function could look as follows:

      void PlaySound(int Volume)      {      } 

The problem here is that each time the programmer calls this function like this:


The programmer needs to continually specify a volume, even though most of the time it will not change. Thankfully, C++ offers the option of default arguments in such cases, whereby if no argument is provided, a default is assumed. To do this, a function should be declared in the following form:

DataType FunctionName (Argument1 = Default)


      void PlaySound (int Volume = 100) 

Therefore, we can call the function with the default value as follows:


And call the function with a different value as follows:


Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net