Given a program
#include <iostream>
using namespace std;
int main()
{
const size_t DoW = 7;
const unsigned int DAYS_OF_WEEK = static_cast<unsigned int> (DoW);
unsigned int dayOfFirstDay = 0;
unsigned int _firstDayOfWeek = 1;
unsigned int diff = (DAYS_OF_WEEK+ (dayOfFirstDay - _firstDayOfWeek) ) % DAYS_OF_WEEK;
cout << "diff = (" << DAYS_OF_WEEK << " + (" << dayOfFirstDay << " - " << _firstDayOfWeek << ")) %" << DAYS_OF_WEEK
<< " = " << diff << endl;
return 0;
}
The output of that program is
diff = (7 + (0 - 1)) %7 = 6
which is expected. But a modified program without static_cast
#include <iostream>
using namespace std;
int main()
{
const size_t DAYS_OF_WEEK = 7;
unsigned int dayOfFirstDay = 0;
unsigned int _firstDayOfWeek = 1;
unsigned int diff = (DAYS_OF_WEEK+ (dayOfFirstDay - _firstDayOfWeek) ) % DAYS_OF_WEEK;
cout << "diff = (" << DAYS_OF_WEEK << " + (" << dayOfFirstDay << " - " << _firstDayOfWeek << ")) %" << DAYS_OF_WEEK
<< " = " << diff << endl;
return 0;
}
outputs
diff = (7 + (0 - 1)) %7 = 3
which is not expected. Why?
(Both programs are compiled with g++ 9.3.0 on Ubuntu 64 Bit)