https://rentry.org/PPP2_p284

// Code derived from Stroustrup's PPP2 book
// § 8.5.7 Argument checking and conversion
//  -and beginning on p 284

#include <iostream>

using namespace std;

typedef double T;

void f(T x);       // declaration of f()
void f(double x);  // re-declaration of f() (types match, OK)
void f(double) {}  // definition of f()

int main()
{
  T y = 3.1415;

  f(y);

  T x = y;  // initialize x with y (see §8.2.2)

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

void g(int y)
{
  f(y);

  double x = y;  // initialize x with y (see §8.2.2)

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

//---

void ff(int x);  // decl
void ff(int) {}  // defn

void gg(double y)
{
  ff(y);      // how would you know if this makes sense?
  int x = y;  // how would you know if this makes sense?

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

// If you really mean to truncate a double value to an int, say so explicitly
void ggg(double x)
{
  int x1 = x;  // truncates x
  //
  int x2 = int(x);
  int x3 = static_cast<int>(x);  // very explicit conversion (§17.8)

  ff(x1);
  ff(x2);
  ff(x3);

  ff(x);  // truncates x
  //
  ff(int(x));
  ff(static_cast<int>(x));  // very explicit conversion (§17.8)
}

build & run:

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

PrevUpNext

Edit
Pub: 04 Apr 2023 15:04 UTC
Edit: 03 May 2023 00:37 UTC
Views: 328