2016-10-29 34 views
2

新手指针/地址优化问题。如何避免time_t变量?

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

/* ------------------------------------------------------------- 
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变量跳过这一步。

+3

不要打扰。这不太可能导致更优化的代码。只要现在编写代码(这可以更容易阅读),并让编译器(现在非常好)来完成它的工作。 – kaylum

回答

1

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

这称为一个 “复合文字”。

+1

而且是原来难以阅读的十倍。而且,最有可能的是,没有一点效率更高。没有冒犯的意图 - 毕竟你只是正确地回答了这个问题,但我会解雇任何在我的代码中构建类似内容的人...... – tofro

+1

我完全同意。我从来没有见过任何人在15年以上的C编程中做到这一点。我甚至不记得我是如何知道这一点的。可能来自另一个stackoverflow问题。 –