I wrote the following piece of code to advance the input date to the following calendar date. This works well when tested in a dummy source file compiled with g++ 4.1.2
However, when running the following code from within my firm's simulator(intricate details of which are unavailable to me at this point), it breaks on 20021027; i.e. for dates other than 20021027, it works as intended but for 20021027, it returns 20021027 itself.
Please advise as to what could be going wrong?
int nextday(const int &date, int n=1)
{
struct tm curr_time;
int yyyy = curr_time.tm_year = date/10000-1900;
int mm = curr_time.tm_mon=(date/100)%100-1;
int dd = curr_time.tm_mday=date%100;
curr_time.tm_min=0;
curr_time.tm_sec=0;
curr_time.tm_hour=0;
time_t next = mktime(&curr_time) + 24*60*60*n;
struct tm new_time;
localtime_r(&next,&new_time);
yyyy = 1900 + new_time.tm_year;
mm = 1 + new_time.tm_mon;
dd = new_time.tm_mday;
return (10000*yyyy+100*mm+dd);
}
I don't see why that one date would cause problems, but I don't understand why you're doing things the hard way. Just add one to the
tm_mday
field before callingmktime
, then extract the corrected values from thestruct tm
you passed intomktime
. (There's a reason why the pointer intomktime
points to non-const.) Something like:(You might want to add some sanity checks, i.e. verify that the
int
passed in really does represent a date in the expected format, and thatn
is in some reasonable range. Or if you can influence the decision, use some standard date format, so you don't have to.)Anyway, I'd suspect some problem in the simulator, especially if it works with the same value locally.
you simply reached integer limit of 2147483647, wich is then rounded down.
Always check in your code if any number goes above that value^^. switching to unsigned should fix that (or well just remand the problem to 4294967295)
EDIT: you are correct. My answer is wrong.