如何避免time_t变量?

时间:2016-10-29 06:12:36

标签: c pointers localtime

新手指针/地址优化问题。

作为练习,我写了这段代码。

/* -------------------------------------------------------------
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;

}

现在,出于练习目的,我想将这两行放在一行中,从而避免变量time_seconds。

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

localtime需要time_t变量的地址。我不知道如何使用这个time_t变量跳过这一步。

1 个答案:

答案 0 :(得分:1)

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

这称为制作"复合文字"。