https://rentry.org/PPP2_p267

// 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

PrevUpNext

Edit
Pub: 04 Apr 2023 14:30 UTC
Edit: 14 May 2023 11:37 UTC
Views: 681