CPP Function Default Parameters

Function and Default Parameters.

  • A default value is a value to use if none is supplied.
  • You can setup default values to parameters within the prototyping of the function. You should not do this at the implementation of the function.
    Default Parameters example:
    Source code Result
    // Demonstrates use
    // of default parameter values
    #include <iostream>
    // Prototyping of the function  
    int getVolume(int length, int width = 25, int height = 1);
    
    int main() {
      int length = 100;
      int width = 50;
      int height = 2;
      int volume;
      // The result of this should be 100*50*2=10000  
      volume = getVolume(length, width, height);
      std::cout << "1.volume equals: " << volume << "\n";
      // The result of this should be 100*50*1=5000   
      volume = getVolume(length, width);
      std::cout << "2.volume equals: " << volume << "\n";
      // The result of this should be 100*25*1=2500   
      volume = getVolume(length);
      std::cout << "3.volume equals: " << volume << "\n";
      return 0;
    }
    // Implementation of the function  
    int getVolume(int length, int width, int height) {
      return (length * width * height);
    }
    1.volume equals: 10000
    2.volume equals: 5000
    3.volume equals: 2500
    Rules in assigning default parameters:
    • You can assign a default value to Param2 only if you have assigned a default value to Param3.
    • You can assign a default value to Param1 only if you've assigned default values to both Param2 and Param3.

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.