C++ Functions and Parameter Passing

Pass by Value

  • can not change the value of the actual parameter

Pass by Reference

  • can change value of parameter

 

C++ Arrays

  • passed by reference

C++ non-arrays

  • normally passed by value

Example C++ how to pass by reference

  • void function (CarType& car, float x)
  • x is by value, car is by reference
  • can do in function car.price = X*33.3;
  • invocation of fuction      function(myCar, 0.03);

void  AdjustForInflation(CarType&  car,  float  perCent)

// Increases price by the amount specified in perCent	
{

    car.price = car.price * perCent + car.price;  
   
} ;



SAMPLE CALL

AdjustForInflation(myCar, 0.03);

Example C++ how to pass by value

bool LateModel(CarType car, int date)
// Returns true if the car’s model year is later than or
// equal to date; returns false otherwise.

{ return ( car.year >= date ) ; } ;

  • invocation of function SAMPLE CALL

    if ( LateModel(myCar, 1995) )
            std::cout << myCar.price << std::endl ;