MISRA Discussion Forums
Rule 7.0.5, example non-compliant with 7.0.6? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=188)
+---- Forum: 4.7 Standard conversions (https://forum.misra.org.uk/forumdisplay.php?fid=193)
+---- Thread: Rule 7.0.5, example non-compliant with 7.0.6? (/showthread.php?tid=1735)



Rule 7.0.5, example non-compliant with 7.0.6? - cgpzs - 17-04-2025

Rule 7.0.5 presents this example:

Code:
u8a += static_cast< uint32_t >( u8b ) // Compliant - u8a -> unsigned int

Yes, compliant with 7.0.5. But this code then violates 7.0.6, since there is an implicit narrowing conversion from uint32_t to uint8_t in the assignment, right?

Code:
u8a = (uint32_t)(u8a) + (uint32_t)(u8b);

So, how are we supposed to write this type of code? Like this?

Code:
u8a = static_cast<std::uint8_t>(static_cast<std::uint32_t>(u8a) + static_cast<std::uint32_t>(u8b));

Does that really make the code safer?


RE: Rule 7.0.5, example non-compliant with 7.0.6? - misra cpp - 19-05-2025

"... Yes, compliant with 7.0.5. But this code then violates 7.0.6, since there is an implicit narrowing conversion from uint32_t to uint8_t in the assignment, right?"

No. The introduction to the section that includes 7.0.5. and 7.0.6 says "Note: compound assignments are not assignments", so 7.0.6 does not apply to a compound assignment.

We recognise that it may be surprising that a += b; is treated differently to a = a + b; but we failed to find an acceptable form of words to say 'treat a = a + ....' as 'a += ....'

The example: u8a += static_cast< uint32_t >( u8b ); is correct and compliant


RE: Rule 7.0.5, example non-compliant with 7.0.6? - cgpzs - 20-05-2025

(19-05-2025, 03:30 PM)misra cpp Wrote: "... Yes, compliant with 7.0.5. But this code then violates 7.0.6, since there is an implicit narrowing conversion from uint32_t to uint8_t in the assignment, right?"

No.  The introduction to the section that includes 7.0.5. and 7.0.6 says "Note: compound assignments are not assignments", so 7.0.6 does not apply to a compound assignment.

We recognise that it may be surprising that  a += b;  is treated differently to  a = a + b;  but we failed to find an acceptable form of words to say  'treat a = a + ....'  as  'a += ....'

The example:  u8a += static_cast< uint32_t >( u8b );  is correct and compliant

Thanks! I (and my static analyzer supplier Smile ) totally missed that little bit. As a suggestion, I think it would be good to remind about that directly inside Rule 7.0.6, in a future revision.


RE: Rule 7.0.5, example non-compliant with 7.0.6? - misra cpp - 18-07-2025

Thread now closed - please post any follow-up as a new thread