c++

Page 91

3.8 Functions double square(double x) { return x*x }

75

// definition of a function

So can we de ne yet another taking a long double and returning a long double. These versions of the square() function can coexist in a program. The compiler can decide which version to use by comparing the type of the argument with the type of the parameter. Using the same name for similar operations on di erent types is called overloading. Return type is not considered in overloading resolution. For example, double a = double b =

square(5) square(5.0)

// call int square(int) // call double square(double)

Neither are functions declared in di erent scopes. An example is: int cubic(int) double fg(int i) { double cubic(double) return cubic(i) }

// no overloading occurs here // call double cubic(double)

In call cubic(i), the function cubic(double) declared in the same scope, is used.

3.8.3 Argument Passing

There are two argument passing mechanisms in C++: pass by value and pass by reference. In pass by value, the argument is rst evaluated at the time of the function call, and its value becomes the value of the parameter during the execution of the function. The default is pass by value, as in the following example. int pass_val(int x) { x = x*x return x + 5 }

// default is pass by value

int i = 5 int j = pass_val(i) // now i = 5, j = 30

In the function call j = pass val(i) the value of the argument i which is 5 is passed to the parameter x: The function pass val() starts with the value x = 5 executes its block of statements, and returns value 30 to j: Thus after the function call, i = 5 and j = 30: In pass by reference, an argument must be a variable with allocated location and the argument is passed to the function as a reference, so that


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.