简体   繁体   中英

simple c program does not produce required output

I am using the following program to print the current time

int main() 
{
  printf("%s",__TIME__);
  return 0;
}

It works only for the first time. If I run it after sometime it again gives the same old time.

Why do I need to do to refresh the time ?

__TIME__ is a standard predefined macro that expands to a string constant that describes the time at which the preprocessor is being run .

It is replaced by the preprocessor just before the compilation. So it does not change with different runs. But if you recompile your program you'll see the change.

To get the current time of the day you can use the time , localtime and asctime functions as:

time_t rawtime;
struct tm * timeinfo;

time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );

__TIME__ is a macro being set by your compiler. Since it's fixed at compile time, running your program later won't change the output. You can call gettimeofday() or time() or even some other functions to get the time/date at runtime. ctime() and its related functions can generate more useful strings for you.

What everyone is saying about __TIME__ is correct. Here's a link about the ctime library.

http://www.cplusplus.com/reference/clibrary/ctime/ctime/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM