https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92220

R. Diez <rdiez-2006 at rd10 dot de> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |rdiez-2006 at rd10 dot de

--- Comment #7 from R. Diez <rdiez-2006 at rd10 dot de> ---
This shortcoming has annoyed me for quite some time.

Here is the test case I am using to convey the issue:

// Compile with -Wconversion

#include <stdint.h>

int main ( void )
{
  volatile uint64_t a = 123;
  volatile uint16_t b = 2;

  // warning: conversion from 'long unsigned int' to 'uint16_t'
  // {aka 'short unsigned int'} may change value [-Wconversion]

  uint16_t result = a % b;

  return result;
}

It is available here to play with:
https://godbolt.org/z/aKPqEozjW

I am trying to write a safe wrapper to prevent the warning like this:

template < typename TypeA, typename TypeB >
TypeB ModuloToSmallerSize ( const TypeA a, const TypeB b ) throw()
{
  if constexpr ( sizeof( TypeA ) <= sizeof( TypeB ) )
  {
    // If there is no need for tricks, do not use any.
    return a % b;
  }
  else
  {
    return static_cast< TypeB >( a % b );
  }
}

But I am not sure whether that implementation is a good idea. Should I check
whether both integer types are signed or both are unsigned? Or does it not
matter at all?

Reply via email to