1

I'm currently updating some code and I ran into a spot where the code makes an assumption about the size of a time_t variable being the same as a signed long. This code works on our previous platform (so apparently on the Coldfire that was true) but we're moving to a new platform.

Now I know that we should not be making assumptions about the size of a time_t variable, since that's not well defined. But I really don't want to rewrite all the lines of code which work based on this assumption at the moment.

Ideally I'd like to do something like:

#if sizeof(time_t) != sizeof(LONG)
#error size assertion failed
#endif

once and be done with it. I'm aware that sizeof() can't be used in a conditional preprocessor like that so it's out of the question.

So I'm wondering, is there any way I can know the number of bytes that a time_t will take such that it can be used in a preprocessing conditional?

Mike
  • 47,263
  • 29
  • 113
  • 177
  • 4
    See http://stackoverflow.com/questions/4079243/how-can-i-use-sizeof-in-a-preprocessor-macro and http://www.pixelbeat.org/programming/gcc/static_assert.html – devnull Jun 20 '13 at 15:24
  • [sizeof in define](http://c-faq.com/cpp/ifsizeof.ct.html) from comp.lang.c faq. – devnull Jun 20 '13 at 15:30

1 Answers1

3

If you're after a compile-time failure then just do something like this

{
    char s1[+sizeof(time_t) - sizeof(LONG) + 1];
    char s2[-sizeof(time_t) + sizeof(LONG) + 1];
}

Which will fail to build if the sizes differ.

You could put that into a macro, but the error would be rather cryptic.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Works for me, using C11. time_t was sizeof(int) but failed to compile with sizeof( char) –  Jun 20 '13 at 15:30
  • "*... the error would be rather cryptic.*" hehe, and so you really should add a good comment. – alk Jun 20 '13 at 15:30
  • @alk It tells you on what line the error occurs, so its just the matter of adding a comment. –  Jun 20 '13 at 15:32
  • @Armin; I deleted my comment, making yours a little odd. – Bathsheba Jun 20 '13 at 15:38
  • 2
    Can be simplified to one array: `char s[2*(sizeof(time_t) == sizeof(LONG)) - 1];`. Then you can rename `s` to be something more descriptive for the compile time error. – jxh Jun 20 '13 at 15:49
  • @jxh - that's very nice; especially when renaming s; and with some tricker, OP gets their macro. – Bathsheba Jun 20 '13 at 15:50