Search code examples
c++sizeofc-preprocessor

Determine the size of time_t with preprocessor?


Is there a way to know the size of time_t at the time the preprocessor is running?

I'd like to know whether time_t is an int32_t or int64_t and I'd like the trick to work under Linux (POSIX) and Windows (and if possible under Mac OS/X). It'd like it early on so I can do something like this:

#if time_t == _32BIT
typedef zint32_t my_time_t;
#else
typedef zint64_t my_time_t;
#endif

My zint32/64_t types are automatically initialized to zero. That works great for most types, but it is problematic with time_t at this point. Unless I can determine the size at compile time with the preprocessor.


Solution

  • There is no standard macro to detect the size of time_t, and you cannot compute the size of a type during preprocessing (since "types" do not exist during preprocessing). You can, however, achieve your desired result using templates:

    #include <ctime>
    #include <utility>
    
    typedef std::conditional<
        sizeof(time_t) == 8,
        zint64_t,
        zint32_t
    >::type my_time_t;
    

    Do note that sizeof(time_t) is implementation-defined and may be something other than four or eight bytes. You'll need to be sure to account for this, either by ensuring that on all of your target platforms it is either four or eight bytes, or by adding additional logic to handle other sizes.