Furthermore, compare these:
1 2 3 4 5 6 7
|
int mult( int x ) {
return x * snafu;
}
int mult( int x, int y ) {
return x * y;
}
|
Which one of them would you use in here:
1 2 3 4 5 6 7 8
|
int snafu {42};
int main() {
for ( int foo = 1; foo < 5; ++foo ) {
// I want to show: foo * (foo+1)
// and I have to use mult() to do the multiplication
}
}
|
If a function uses a global value, then the function
depends on that value. Is restricted. Is less flexible.
The latter mult() has no such dependencies. All necessary data arrives via parameters. (You can still call
mult(foo,snafu)
to get the same result as from the other version.)
Another example:
1 2 3 4 5 6 7 8 9
|
std::ostream & print( int x ) {
std::cout << x;
return std::cout;
}
std::ostream & print( std::ostream& out, int x ) {
out << x;
return out;
}
|
The first print() can output to exactly one stream.
The user can choose the stream that the second print() writes to.
Lets say there is
class Foo
. Foo has complex constructor and destructor. The program is in (at least) two files:
a.cpp:
1 2 3 4 5
|
#include "Foo.h"
Foo fubar;
// other code
|
b.cpp:
1 2 3 4 5
|
#include "Foo.h"
Foo snafu;
// other code
|
Can you tell off-hand,
when the global fubar and snafu are constructed and when they are destructed?
Alternative:
1 2 3 4 5 6
|
#include "Foo.h"
int main() {
Foo foo;
Foo bar;
}
|
Can you tell off-hand, when the local foo and bar are constructed and when they are destructed?