PrintRectangle() example
rows
and cols
void PrintRectangle(int rows, int cols) {
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= cols; c++) {
cout << "*";
}
cout << endl;
}
}
PrintRectangle(3, 4);
**** **** ****
void and does not have
a return statement
// This is WRONG... the function doesn't return back an answer! int ans = PrintRectangle(3, 4);
void PrintRectangle(int rows, int cols, char box) {
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= cols; c++) {
cout << box;
}
cout << endl;
}
}
PrintRectangle(2, 5, '?');
????? ?????
char and the 2nd is
an int, the 1st argument should be a char and the
2nd argument an int
void MyFunc(int x) {
int a;
// etc...
}
int main() {
// main's x and a are different than MyFunc's x and a
int a;
int x;
// etc...
}
void functions don't return an answer, they just do something like
output to the console window; non-void functions always return a single answer
void functions are called differently than non-void
functions
// Calling a void function DoSomething(5); // Calling a non-void function cout << GiveAnAnswer(5);
void functions do not have a return statement but
non-void functions do
void function must
return a value
// PROBLEM: what does the function return if x >= 10?
int DoSomething(int x) {
if (x < 10) {
return 5;
}
}
#include <iostream>
using namespace std;
void A(int x) {
cout << x;
}
void B() {
A(5);
}
void C(int x, int y) {
cout << x + y;
}
int main() {
B();
C(2, 3);
return 0;
}
|
Here is the structure chart:
|
A was defined before function B
which was necessary for it to compile properly. If they were switched, the compiler
would complain when it reached this line:
A(5);because the compiler would not yet know about function
A. Therefore,
functions need to be defined bottom-up from the ordering in the structure chart