MISRA Discussion Forums
Does "u8 = 6L;" violate rule 10.3 - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.10 The essential type model (https://forum.misra.org.uk/forumdisplay.php?fid=165)
+---- Thread: Does "u8 = 6L;" violate rule 10.3 (/showthread.php?tid=1258)



Does "u8 = 6L;" violate rule 10.3 - misra-c - 17-06-2016

The following question has been submitted to the working group.

Please can you explain which of the following are non-compliant with rule 10.3.
Code:
typedef signed char sint8_t;
typedef unsigned char uint8_t;
sint8_t s8;
uint8_t u8;
s8 = 6L;      /* not compliant - STLR is essentially signed long */
u8 = 6UL;     /* not compliant - as above */

u8 = 6;       /* compliant by exception 1 */
u8 = 6L;      /* compliant or not ? */
Exception 1 says that
Quote:a non-negative integer constant expression of essentially signed type may be assigned to an object of essentially unsigned type if its value can be represented in that type
The value of 6L can be represented in an unsigned char type and so this implies that the above assignment is compliant by exception 1. However this is not consistent with u8 = 6UL being non-compliant.


Re: Does "u8 = 6L;" violate rule 10.3 - misra-c - 17-06-2016

The intention was that the exception should only apply to expressions with an essential type whose rank is no greater than signed int. In other words:
"u8 = 6L;" is non compliant as the essential type of 6L is signed long.

This will be corrected in a future Technical Corrigendum.


Re: Does "u8 = 6L;" violate rule 10.3 - grunwald - 14-02-2020

This change has the unfortunate effect that:

Code:
uint16_t x = 50000;

now is no longer valid if int is 16 bits.


Re: Does "u8 = 6L;" violate rule 10.3 - misra-c - 01-06-2020

The TC1 Clarification of Exception 1 of rule 10.3 states.
Quote:"An essentially signed integer constant expression, with a rank no greater than signed int, may be assigned to an object of essentially unsigned type if its value can be represented in that type.
The C standard type ( and essential type) of 50000 is "signed long" for a 16-bit int. TC1 clarifies that exception 1 does not apply.
The code should be written as uint16_t x = 50000U;