Narrowing Conversion of unsigned int to short unsigned int

前端 未结 2 1643
情书的邮戳
情书的邮戳 2021-01-22 07:24

warning: narrowing conversion of \'(stride * 4u)\' from \'unsigned int\' to \'WORD {aka short unsigned int}\' inside { } is ill-formed in C++11 [-Wnarrowing]

2条回答
  •  失恋的感觉
    2021-01-22 07:47

    stride is unsigned so its value could be too large to fit into an unsigned short. Furthermore sizeof has type std::size_t which is also larger than WORD.

    If you make stride a const unsigned, then the compiler can see that the actual value 12 does fit into unsigned short and the error goes away. But if it is not a constant, you need to explicitly guarantee that the calculation will fit because initializers inside braces are not allowed to truncate or overflow. ("Narrowing" refers to losing data, alluding to chopping off digits on one end of a number.)

    Just use static_cast< WORD >( … ).

提交回复
热议问题