LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   (void)time(&cur_time); Why did the author put (void) here? (https://www.linuxquestions.org/questions/programming-9/void-time-and-cur_time-%3B-why-did-the-author-put-void-here-871478/)

e3399 03-28-2011 10:16 AM

(void)time(&cur_time); Why did the author put (void) here?
 
Code:

A program from 《BeginningLinuxProgramming》.
#include <stdio.h>
#include<unistd.h>
#include<time.h>

int main (int argc, char **argv)
{
    int i;
    time_t cur_time;
    struct tm *the_time;

    (void)time(&cur_time);////I don't think it needs (void) here.
    the_time = gmtime(&cur_time);
    printf("Year  Month  day\n");
    printf("%d  %d  %d\n", the_time->tm_year + 1900, the_time->tm_mon + 1,\
            the_time->tm_mday);
    printf("Time:%d:%d:%d\n", the_time->tm_hour, the_time->tm_min,\
            the_time->tm_sec);

    return 0;
}

Any help will be appreciated.


dwhitney67 03-28-2011 10:19 AM

The void is merely to tell the program that the return value should be ignored. Certain compiler flag(s) may issue a warning if the void is not specified. The author of the code could just have easily done something like:
Code:

time_t cur_time = time(NULL);
You should read the man-page for time() to get further enlightened.

e3399 03-28-2011 11:21 AM

Quote:

Originally Posted by dwhitney67 (Post 4306378)
The void is merely to tell the program that the return value should be ignored. Certain compiler flag(s) may issue a warning if the void is not specified. The author of the code could just have easily done something like:
Code:

time_t cur_time = time(NULL);
You should read the man-page for time() to get further enlightened.

Thanks.
But I still don't understand.Why the return value should be ignored here.Without (void),gcc didn't show any warning.
Do you mean we should put(void) before a function whose return value is not used.

dwhitney67 03-28-2011 11:45 AM

Pardon my choice of words earlier... I erred in using the word "should"; I meant to use "can".

One does not need to explicitly ignore the return value; some programmers just like to be over-zealous with their code. I briefly glanced through the man-page for gcc to see if I can locate an option that would produce a warning that the return value is not be used, but I could not find one.

Suffice to say, I've been developing code for over 20 years; not once have I ever explicitly placed a void in front of a function that is called.


All times are GMT -5. The time now is 10:08 PM.