1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | // Code derived from Stroustrup's PPP2 book
// § 8.4 Scope
// -and beginning on p 267
#include <iostream>
#include <vector>
using namespace std;
void f(int x) // f is global; x is local to f
{
int z = x + 7; // z is local
cout << z << '\n';
}
int g(int x) // g is global; x is local to g
{
int f = x + 2; // f is local
return 2 * f;
}
//---
int my_max(int a, int b) // my_max is global; a and b are local
{
// The ?: construct is called an arithmetic if or a conditional expression.
// -AKA 'ternary conditional' [1]
// The value of (a>=b)?a:b is a if a>=b and b otherwise.
return (a >= b) ? a : b;
}
int my_abs(int a) // not my_max()'s a
{
return (a < 0) ? -a : a;
}
//---
int my_max2(int a, int b) // max2 is global; a and b are local
{
int m; // m is local
if (a >= b)
m = a;
else
m = b;
return m;
}
//---
// no r, i, or v here ...
class My_vector {
vector<int> v; // v is in My_vector's (private) class scope
public:
int largest() // largest() is in My_vector's (public) class scope
{
// the smallest non-negative int
int r = 0; // r is local within largest()
for (unsigned i = 0; i < v.size(); ++i) // i is in for statement's scope
r = my_max(r, my_abs(v[i]));
// ... no i here
return r;
}
// ... no r, or i here
};
// ... and again; no r, i, or v here
//---
int x; // global variable - avoid those when you can
int y; //
int f()
{
int x; // local variable
x = 7; // the local x
{
[[maybe_unused]] int x = y; // inner scope local x initialized by global y
++x; // the x from the previous line (not the one above that)
}
++x; // the x from the first line of f()
return x;
}
//---
class C {
public:
void f();
// a member definition can be inside it's class ...
void g()
{
// ...
}
// ...
};
// ... or, a member definition can be outside it's class (but not both)
void C::f()
{
// ...
}
//---
int main()
{
f();
return my_abs(my_max(f(), g(0)) - my_max2(f(), g(1)));
}
//------------------------------------------------------------------------------
// 1. https://en.cppreference.com/w/cpp/language/operator_other
|
build & run:
g++ -std=c++20 -O2 -Wall -pedantic ./ch_08/main_p267.cpp && ./a.out