2016-10-29 97 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問題。 –