https://rentry.org/PPP2_p308

// Code derived from Stroustrup's PPP2 book
// § 9.4.1 struct and functions
//  -and beginning on p 308

#include <iostream>

using namespace std;

// simple Date (too simple?):
struct Date {
  int y;  // year
  int m;  // month in year
  int d;  // day of month
};

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

// helper functions:

void init_day(Date& dd, int y, int m, int d)
{
  // check that (y,m,d) is a valid date
  // if it is, use it to initialize dd

  cout << dd.y << y << m << d << '\n';  // rm's 'unused variable' error
}

void add_day(Date& dd, int n)
{
  // increase dd by n days

  cout << dd.y << n << '\n';  // rm's 'unused variable' error
}

void f()
{
  Date today;
  init_day(today, 12, 24, 2005);  // oops! (no day 2005 in year 12)
  add_day(today, 1);
}

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

int main()
{
  // this C++ attribute prevents an 'unused variable' error by compiler
  [[maybe_unused]]  //
  Date today;       // a Date variable (a named object)

  // set today to December 24, 2005
  today.y = 2005;
  today.m = 24;
  today.d = 12;

  // this C++ attribute prevents an 'unused variable' error by compiler
  [[maybe_unused]]  //
  Date x;           //
  x.y = -3;
  x.m = 13;
  x.d = 32;

  // Was year 2000 a leap year? Are you sure?
  Date y;
  y.y = 2000;
  y.m = 2;
  y.d = 29;

  init_day(y, 2000, 1, 1);
  add_day(y, 28);
}

build & run:

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

PrevUpNext

Edit
Pub: 06 Apr 2023 14:29 UTC
Edit: 03 May 2023 01:01 UTC
Views: 361