Functions

The program asks the user to enter the length and width. A function is called to print the area.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Area program: using area function that returns nothing
#include <iostream>
using namespace std;
void area(double,double); // receives length & width, prints area
int main(){ 
  double length, width;
  cout<<"Enter length: ";
  cin>>length;
  cout<<"Enter width: ";
  cin>>width;
  area(length, width); // calls function area
  system("Pause");
  return 0;
} // main
void area(double l, double w) { // print the area given l and w
  double a;
  a=l*w;
  cout<<"The area is "<<a<<"\n";
} // area 
CODE
Output:
Enter length: 8
Enter width: 7
The area is 56
Press any key to continue . . .

The number of parameters in a function must match the number of arguments in the calling statement. For example, if a function is supposed to receive one integer, and the calling statement is passing two doubles, the compiler will know that it is an error.

C++ (and most modern programming languages) is a single pass compilers. That means that when you call a function, C++ must already know the correct syntax of the function. The compiler can compare the functions parameters to the values that you are passing to it (the arguments) to see if it is called correctly. One way to do that is to declare the other function before main or the calling statements. Another way is to put a function prototype (line 4) before main, and then put the function definition later (lines 15-19.)

The results are the same either way.

NEXT: Functions with pass by reference