Search code examples
cstdtime-t

search for uses of int used instead of time_t


I have a rather large c-code base, where every once in a while int is used instead of time_t. Any good ideas as to how to deal with this. Should I search the entire standard library for functions that either return time_t or take it as argument, or is there a smarter way?

As I understand it, time_t will be 64 bit on a 64-bit system, at least on my system, which is 64 bit. An int will only be 32 bit on a 64-bit system. Which means that such an int will run out in 2038 if used as time_t.


Solution

  • Assuming you're using gcc or clang, if you compile with the -Wconversion flag, it will warn you about converting from a larger type to a smaller type.

    #include <stdio.h>
    #include <time.h>
    
    int main()
    {
        time_t t = time(NULL);
        int i = t;
    
        printf("i=%d, t=%ld\n", i, t);
    
        return 0;
    }
    
    [dbush@db-centos7 ~]$ gcc -g -Wall -Wextra -Wconversion -o x1 x1.c
    x1.c: In function ‘main’:
    x1.c:7:5: warning: conversion to ‘int’ from ‘time_t’ may alter its value [-Wconversion]
         int i = t;
         ^