Function prototype A function must be declared before
Function prototype • A function must be declared before it can be referenced. • One way to declare a function is to insert a function prototype before the main function. • Function prototype tells the C++ compiler the data type of the function and the arguments, the correct number of arguments, and the correct order of arguments. • The data type of a function is determined by the type of value returned by the function. • It does not specify the function operation. You need to provide a definition for each function.
Function definition and function prototype 1. // A programmer-defined square function 2. #include <iostream> 3. int square (int); // Function prototype 4. 5. int main() 6. { 7. int x; 8. for (x = 1; x <= 10; x++) 9. cout << square(x) << endl; 10. return 0; 11. } 12. int square (int y) 13. { 14. return y * y; 15. } // Function definition
Example • • • square function gets the value of x. square function calculates x * x. The result is passed back to the cout function displays the result. This process is repeated ten times using the for repetition structure. 1 4 9 Output 16 25 36 49 64 91 100
Function without argument Example: void display_information(void); • The function display_information is a void function, returns nothing. • Second void indicates that display_information expects no arguments.
Function with argument Example: int square(int); // prototype • The int in parenthesis informs the compiler that function square expects to receive an integer value from the caller. • The int to the left of square informs the compiler that it returns an integer result to the caller.
Void function with input argument Example: void print_num(int); // prototype • The int in parenthesis informs the compiler that function print_num expects to receive an integer value from the caller. • The void to the left of the function print_num informs the compiler that it returns nothing to the caller.
- Slides: 6