Function Calls
Sample program
// Calculating powers with // the standard function pow() #include <iostream> // Declaration of cout #include <cmath> // Prototype of pow(), thus: // double pow( double, double); using namespace std; int main() { double x = 2.5, y; // By means of a prototype, the compiler generates // the correct call or an error message! // Computes x raised to the power 3: y = pow("x", 3.0); // Error! String is not a number y = pow(x + 3.0); // Error! Just one argument y = pow(x, 3.0); // ok! y = pow(x, 3); // ok! The compiler converts the // int value 3 to double. cout << "2.5 raised to 3 yields: " << y << endl; // Calculating with pow() is possible: cout << "2 + (5 raised to the power 2.5) yields: " << 2.0 + pow(5.0, x) << endl; return 0; }
Screen output
2.5 raised to the power 3 yields: 15.625 2 + (5 raised to the power 2.5) yields: 57.9017
Function Calls
A function call is an expression of
the same type as the function and whose value corresponds to the return value.
The return value is commonly passed to a suitable variable.
Example:
y = pow( x, 3.0);
In this example the function pow()is
first called using the arguments x and 3.0, and the result, the power x3,
is assigned to y.
As the function call represents a value, other operations are also
possible. Thus, the function pow() can be used to
perform calculations for double values.
Example:
cout << 2.0 + pow( 5.0, x);
This expression first adds the number 2.0
to the return value of pow(5.0,x), then outputs the
result using cout.
Any expression can be passed to a function as an argument, such as a constant or an arithmetical expression.
However, it is important that the types of the arguments correspond to those
expected by the function.
The compiler refers to the prototype to check that the function
has been called correctly. If the argument type does not match exactly to the
type defined in the prototype, the compiler performs type conversion, if
possible.
Example:
y = pow( x, 3); // also ok!
The value 3 of type int is passed to the
function as a second argument. But since the function expects a double value, the compiler will perform type conversion from
int to double.
If a function is called with the wrong number of arguments, or if
type conversion proves impossible, the compiler generates an error message. This
allows you to recognize and correct errors caused by calling functions at the
development stage instead of causing runtime errors.
Example:
float x = pow(3.0 + 4.7); // Error!
The compiler recognizes that the number of arguments is
incorrect. In addition, the compiler will issue a warning, since a double, i.e. the return value of pow(), is assigned to a float type
variable.
1 Comments
Thank you for this information…
ReplyDeleteAluminium Scaffolding Manufacturer In Hyderabad