DrawRectangle
example
rows
and cols
void DrawRectangle(int rows, int cols) { for (int r = 1; r <= rows; r++) { for (int c = 1; c <= cols; c++) cout << "*"; cout << endl; } }
DrawRectangle(3, 4);
**** **** ****
void
and does not have
a return statement
// This is WRONG... the function doesn't return back an answer! int ans = DrawRectangle(3, 4);
void DrawRectangle(int rows, int cols, char box) { for (int r = 1; r <= rows; r++) { for (int c = 1; c <= cols; c++) cout << box; cout << endl; } }
DrawRectangle(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... } void main() { // main's x and a are different than MyFunc's x and a int x, a; }
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
int DoSomething(int x) { if (x < 10) return 5; // oh oh... what does the function return if x >= 10? }
#include <iostream> using namespace std; void A(int x) { cout << x; } void B() { A(5); } void C(int x, int y) { cout << x + y; } void main() { B(); C(2, 3); } |
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