Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 10.5
#4
1) In the text above that particular example we can read: "In either case the value of result is 0xfa, but 0x0a may have been expected. This danger is avoided by inclusion of the cast as shown below:"

As I can see it, that text really leaves little room for other results than 0x0a, I would have expected the example not to give the result 0xfa nor 0x0ffa, which is the danger that the text warns us about.


2 + 3) If the example indeed intends to give the very confusing result 0x0FFA, then I assume that the cast is there as a futile attempt to ensure that the ~ operation is made on uint16_t rather than uint8_t. That is, I assume that the typecast is not added as an attempt to conform with rule 10.5, but is rather part of the original code written by someone who is not aware of the integer promotions. The variable port will first be explicitly typecasted to uint16_t, and then before the ~operator is executed, "port" will either remain uint16_t (on a 16-bit machine where int is 16 bit) or it will be implicitly typecasted to the type "int" by the integer promotions. In either case, the explicit typecast to uint16_t is completely pointless. The signedness of int is not important here, since a final typecast of the result is made later.

If the explicit cast is there as a failed attempt to make "port" 16 bit, and is not something that was added as an attempt to conform with rule 10.5, yes in that case the code would indeed be compliant, if not very intuitive. The cast is very confusing for the reader, since the chapter is there to enlighten people of the dangers with implicit typecasts.

Also, if the average programmer is writing code that appends 0xFF in front of a value, they do not usually write something that relies on the size of int to implicitly add a arbitrary number of bytes with the value 0xFF to the variable through the ~ operator. They write something readable:

Code:
uint16_t port16;

  port16 = (uint8_t) ~port;
  port16 |= 0xFF00U;
  port16 >>= 4U;
<t></t>


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)