On 2018-07-19 16:53:11 +0200, Joerg Schilling wrote:
> Vincent Lefevre <vincent-o...@vinc17.net> wrote:
> 
> > The problem is not just the warning. If t is signed,
> >
> >   ((t)(~((t)0) << (sizeof (t)*CHAR_BIT - 1)))
> >
> > will yield undefined behavior due to overflow. This means that
> > compilers may generate code that shows a behavior different from
> > what you expect. Not just recent compilers. Compilers could already
> > do this 20 years ago without a warning. Perhaps some did. Perhaps
> > some users got crashes and other erratic behavior due to that, but
> > did not know the cause or did not notice.
> 
> A compiler that creates other than the expected behavior would need to create 
> intentionally buggy code.
> 
> The question was to create working code that neither creates a warning with 
> newer nor with older compilers. Do you have such code?

There was my answer on stackoverflow:

  
https://stackoverflow.com/questions/5617925/maximum-values-for-time-t-struct-timespec/39782264#39782264

To apply the same idea here:

#include <stdio.h>

#define CHAR_BIT 8
#define TYPE_MSBVAL1(t) ((t)(~((t)0) << (sizeof (t)*CHAR_BIT - 1)))

#define TYPE_MSBVAL2(t) (2 * -((t) 1 << (sizeof(t) * CHAR_BIT - 2)))

int main (void)
{
  printf ("%d\n", TYPE_MSBVAL1(int));
  printf ("%d\n", TYPE_MSBVAL2(int));
  printf ("%ld\n", TYPE_MSBVAL1(long));
  printf ("%ld\n", TYPE_MSBVAL2(long));
  return 0;
}

Contrary to TYPE_MSBVAL1, TYPE_MSBVAL2 doesn't involve
undefined behavior (assuming two's complement).

-- 
Vincent Lefèvre <vinc...@vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)

Reply via email to