C/C++ coding nuance question

Status
Not open for further replies.

stevech

Well-known member
Do you agree that this code, for a 16 or 32 bit size_t target, can omit the and'ing because the cast does the same thing?

(uint16_t)(x & 0xffff)
where x is a uint32_t

Or can one assume the compiler will omit the AND operation whilst doing the cast? Or is it better to not assume such?
(I'm curious as this is part of size-limited code no matter the target CPU)
 
Last edited:
In general there is what is called the 'as if' rule that the compiler is obligated to perform as if the calculation happened.

So, consider the code:
Code:
  uint16_t u16;
  uint32_t u32;

  u16 = u32;                       // implicit and of 0xffff
  u16 = (u32 & 0xffffu);     // explicit and 0f 0xffff, and then implicit 0xffff via the store

Now the optimizer should eliminate the implicit and in the second case, since it should know that the range of the values after doing the AND is 0..0xffff, and a further and would not help. Note, with the as if rule, the compiler might even eliminate the first AND. If for instance it is storing the value into memory, and the machine has a store 16-bit instruction, and the value is not used afterwards, the compiler would just do the store. Similarly, if the machine has instruction variants that do 8 or 16-bit arithmetic inside of 32-bit registers, the compiler can potentially eliminate the zero/sign-extend operations.

Now, in the server side of things, we tend to have the opposite problem, that a lot of people do calculations in 'int', which for various reasons is still 32-bits, even on 64-bit machines. So we see a lot of sign/zero-extend operations to promote the value back to 64-bits.
 
in microprocessors, with GCC and the Teensyduino and Arduino "usual" flags... do you think the AND is necessary along with the cast?

I try to not say u16 = u32; but rather I put in the (uint16_t) cast, so that the code's reader is reminded of the truncation. After the cast, my habit is to not also use the bitwise AND.
 
Last edited:
Status
Not open for further replies.
Back
Top