Static Cast on Initialization

I'm brand new to C++(my only real programming experience is PL/SQL) and have been working through an older C++ book titled Object-Oriented Programming in C++.

One of the example code snippets in the book looks like this, however I've substituted the c-like initialization of variables in preference of uniform initialization.

Below is the code I'm trying to compile, using Microsoft's cl.exe compiler that comes with Visual Studio (I'm not using the IDE).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main() {
  const unsigned long limit {4294967295U};
  unsigned long next {0}, last {1};

  while (next < limit / 2) {
    cout << last << " ";
    long sum {next + last};
    next = last;
    last = sum;
  }

  cout << endl;

  return 0;
}


I'm receiving the error message below:

 
(16) - error C2397: conversion from 'unsigned long' to 'long' requires a narrowing conversion.


I'm assuming this is due to the implicit type casting I'm doing on long sum {next + last}; .

I've tried using a static_cast on the long, but I'm getting a bit confused as to how the syntax should look when casting this variable during the initialization. Would someone be willing to show me how this can be done?

NOTE: I understand I could just change the variable sum to an unsigned long, but I'm really wanting to know how this could be static_cast during initialization of the variable.
Last edited on
 
    long sum = static_cast<long>(next + last);


Be aware that with this cast you might loose information if next + last > LONG_MAX
Thank you Thomas1965, this is exactly what I was looking for. I'm not sure why the book does an implicit cast like it does, in that instance, but it had me wondering how to go about doing this.

One other question that I had was, is it standard for the declaration of a variable to be in a while loop like this? Would that not create a new variable each time the while loop is run and in this case would it be better, memory-wise, to declare the variable outside of the scope of the while loop for this purpose?
Topic archived. No new replies allowed.