Search code examples
c++castingsonarqube

SonarQube requesting explicit cast on the result of the shift operator


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?


Solution

  • 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.