3

I have a ton of similar issues reported by SonarQube:

m_buffer[0]               = static_cast<uint32_t>(headerByte0 << 8);

Where m_buffer is an array of uint32_t, headerByte0 is uint8_t. SonarQube writes:

Add an explicit cast to the result of the "<<" operator.

There is a reference to MISRA C 2004 10.5 and MISRA C++ 2008 5-0-10. Why does SonarQube not recognize the static_cast ? How to solve this?

3
  • 4
    You should cast headerByte0 to uint32_t. uint8_t gets promoted to int in that expression and it does not like shifts on signed integers.
    – mch
    Commented Jul 10 at 8:55
  • 1
    I think it should be static_cast<uint32_t>(headerByte0) << 8
    – kiner_shah
    Commented Jul 10 at 9:02
  • mch, kiner_shah : you seem to be right, this solves the problem. pls. write an answer, detailing why this is necessary
    – G. B.
    Commented Jul 10 at 9:33

1 Answer 1

2

In the line

m_buffer[0]               = static_cast<uint32_t>(headerByte0 << 8);

headerByte0 as an uint8_t gets promoted to int (the signed version), then shifted to the left by 8 as an int, resulting in an int and then gets casted to uint32_t. The left shift of an int might be problematic, you should only shift unsigned integer data types.

The Sonarqube message says, that you should cast the operands of the shift. You cast the result, not the operands.

m_buffer[0]               = static_cast<uint32_t>(headerByte0) << 8u;

should be correct. You cast headerByte0 to uint32_t and then shift it by 8u (the u means it is an unsigned constant), resulting in an uint32_t, perfect for assigning to m_buffer[0], an uint32_t too.

1
  • 1
    thanks for the answer! but the sonarqube message says, i should cast the result of the operator. the misra rules also say, i should cast the result of the operator immediately. none of them says i should cast the operand first...
    – G. B.
    Commented Jul 10 at 10:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.