https://rentry.org/PPP2_p274

// Code derived from Stroustrup's PPP2 book
// § 8.5.2 Returning a value
//  -and beginning on p 274

#include <iostream>
#include <string>
#include <vector>

using namespace std;

typedef int    T;
typedef double V;

T f()  // f() returns a T
{
  V v;

  // ...

  return v;  // error: uninitialized return
}

// warning: buggy code
double my_abs(int x)
{
  if (x < 0)
    return -x;
  else if (x > 0)
    return x;

  // error: no value returned if x is 0
}

void print_until_s(const vector<string> v, const string s)
{
  for (int i = 0; i < (int)v.size(); ++i) {
    if (v[i] == s)
      return;

    cout << v[i] << '\n';
  }
}

int main()
{
  T x = f();
  V v;

  // ...

  // initialize t with v
  T t(v);  // error: v uninitialized when used here

  cout << x << t << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 04 Apr 2023 14:38 UTC
Edit: 02 May 2023 23:34 UTC
Views: 538