Hi Richard Thanks for your help, Best regards David On Tue, Aug 6, 2019 at 7:10 PM Richard Sandiford <richard.sandiford@xxxxxxx> wrote: > David Aldrich <david.aldrich.ntml@xxxxxxxxx> writes: > > Hi > > > > For our large 64-bit C++ project we use gcc compile options: -Wall > -pedantic > > > > We also build the project with Visual C++ and get lots of instances of > > warning C4267, for example: > > > > 'initializing': conversion from 'size_t' to 'unsigned int', possible loss > > of data > > > > To get a similar warning with gcc it seems that I need -Wconversion. > > However, that warning option seems very strict. For example with this > code: > > > > typedef struct > > { > > uint8 x : 4, > > y : 4; > > } myHdr; > > > > unsigned X=1; > > myHdr hdr; > > > > hdr.x = static_cast<uint8_t>(X); > > > > I get warning: > > > > warning: conversion to ‘unsigned char:4’ from ‘uint8_t {aka unsigned > char}’ > > may alter its value [-Wconversion] > > Yeah, it's a long-standing wart that the warning can't be disabled > for bitfields even when, like here, there's an explicit cast to the > underlying type (which is as close as an explicit cast can be). See: > > https://gcc.gnu.org/bugzilla/show_bug.cgi?id=39170 > > (warning: some of the initial responses were somewhat tetchy) > > clang's -Wconversion doesn't warn for this case either, so it looks > like GCC is being stricter than both clang and Visual C++. > > > I have two questions: > > > > 1) What static_cast would I use to fix the above example warning? > > I don't think there is one, but you can use: > > hdr.x = X & 0xf; > > to make the truncation explicit. Neither GCC nor clang warn then. > > I realise that might not be particularly desirable though. > > > 2) Is -Wconversion recommended or is it too fussy in practice? Is there a > > better option? > > -Wconversion is the right option to use. Unfortunately there's > not yet any way of disabling or relaxing the warning for bitfields, > but the PR above is tracking that as a future enhancement. > > Thanks, > Richard >