C11 6.3.2.3 states:
An integer constant expression with the value 0, or such an expression cast to type void *
, is called a null pointer constant
This is the only case in the C language where you can assign a pointer to the value 0
- to get a null pointer. The line in the question can never be used to set a pointer to point at address zero, since assignment of integer values to pointers is invalid C in all other cases.
If we go through the rules of simple assignment C11 6.5.16.1, then there exists no case where the left operand of =
is a pointer and the right operand is an arithmetic type. This rule is very clear in the standard, code such as int* ptr = 1234;
is simply invalid C and has always been invalid C (it is a "constraint violation" of the standard). Compilers letting it through without a warning/error are garbage and not standard conforming.
Simple assignment lists one valid exception (C11 6.5.16.1):
- the left operand is an atomic, qualified, or unqualified pointer, and the right is a null pointer constant
This is the only reason why the code in the question compiles.
Now if you actually wish to point at the hardware address 0, you must write something like this:
volatile uint8_t* ptr = (volatile uint8_t*)0u;
This forces a conversion from the integer 0 into a pointer pointing at address 0. Since the right operand is neither a 0
nor a zero cast to void*
, it is not a null pointer constant, and thus ptr
is not a null pointer.
The C standard is clear and MISRA-C is perfectly compatible with the standard.
Bugs and issues unrelated to the question:
- Not using
volatile
when pointing at a hardware address is always a bug.
- Using
diagBuf[0] + 0x40u
is a bad way of setting a bit to 1. If the bit is already set, then you get a massive bug. Use |
instead.
Assuming diagBuf
is a pointer to byte, then diagBuf[0] = diagBuf[0] + 0x40u;
is a MISRA-C:2012 violation of rule 10.3 since you assign a wider type ("essentially unsigned") to a narrower type. MISRA compliant code is:
diagBuf[0u] = (tm_uint8)(diagBuf[0u] + 0x40u;);