https://rentry.org/PPP2_p262

// Code derived from Stroustrup's PPP2 book
// § 8.2.2 Variable and constant declarations
//  -and beginning on p 262

#include <iostream>
#include <vector>

using namespace std;

int main()
{
  int         a;                // no initializer
  double      d = 7;            // initializer using the = syntax
  vector<int> vi(10);           // initializer using the ( ) syntax
  vector<int> vi2{1, 2, 3, 4};  // initializer using the { } syntax

  const int x = 7;  // initializer using the = syntax
  const int x2{9};  // initializer using the {} syntax

  const int y;  // error: no initializer

  // cout << a << d << x << x2 << '\n';
}

//------------------------------------------------------------------------------

namespace innocent {
void f(int z)
{
  int x;  // uninitialized

  // ... no assignment to x here ...

  x = 7;  // give x a value

  // ...

  cout << x << z << '\n';
}
}  // namespace innocent

//------------------------------------------------------------------------------

namespace dangerous {
void f(int z)
{
  int x;  // uninitialized

  // ... no assignment to x here ...

  if (z > x) {
    // ...
  }

  // ...

  x = 7;  // give x a value

  // ...
}
}  // namespace dangerous

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_08/main_p262.cpp && ./a.out

PrevUpNext

Edit
Pub: 04 Apr 2023 14:15 UTC
Edit: 02 May 2023 22:13 UTC
Views: 367