geohei geohei - 1 month ago 12
C Question

How to avoid time_t variable?

Newbie pointer/address optimization question.

As an exercise, I wrote this code.

/* -------------------------------------------------------------
FUNC : dateplusdays (date plus days)
add/substract days to/from date
days can be positive or negative
PARAMS : date (int, format yyyymmdd), days (int)
RETURNS : date (int, format yyyymmdd)
REMARKS :
---------------------------------------------------------------- */
int dateplusdays(int date_1, int days) {

int year, month, day;
int date_2;
struct tm time;
time_t time_seconds;

year = (int) floor(date_1 / 10000.0);
month = (int) (floor(date_1 / 100.0) - year * 100);
day = (int) (floor(date_1) - month * 100 - year * 10000);

time.tm_sec = 0;
time.tm_min = 0;
time.tm_hour = 0;
time.tm_year = year - 1900;
time.tm_mon = month - 1;
time.tm_mday = day;

time_seconds = mktime(&time) + days * 86400;
time = *localtime(&time_seconds);

date_2 = (time.tm_year + 1900) * 10000 + (time.tm_mon + 1) * 100 + time.tm_mday;

return date_2;

}


Now, for exercise purpose, I'd like to put these 2 lines in one single line, hence avoiding the variable time_seconds.

time_seconds = mktime(&time) + days * 86400;
time = *localtime(&time_seconds);


localtime requires the address of a time_t variable. I don't see how I could skip the step using this time_t variable.

Answer

time = localtime((time_t[]){mktime(&time) + days * 86400});

This is called making a "compound literal".