gpt4 book ai didi

c++ - 混合 C 和 C++ 代码的静态分析怪异符号行为

转载 作者:太空狗 更新时间:2023-10-29 20:49:53 24 4
gpt4 key购买 nike

在混合 C 和 C++ 程序中给出以下定义:

//in a C file.
uint8_t GetSize()
{
return (uint8_t)something;
}

//in the header of the C++ file.

public:
MyClass(){};
private:
uint8_t index_m;

以下两行都为我提供了一个静态工具 (pc-lint) warning 573 .

void MyClass::IncrementWithRollOver(void)
{
index_m = (index_m + 1) % GetSize(); // warning 573 : signed-unsigned mix with divide
}
void MyClass::DecrementWithRollOver(void)
{
index_m = (GetSize() - 1 + index_m) % GetSize(); // warning 573 : signed-unsigned mix with divide
}

我尝试了很多转换,但没有一个能帮助我摆脱这个警告,为什么?

        index_m = (index_m + 1U) % GetSize(); // this one works

index_m = (GetSize() - 1U + index_m) % GetSize();// info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]

index_m = (uint8_t)(index_m + (uint8_t)1) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 732: loss of sign (assignment) ('int' to 'uint8_t' (aka 'unsigned char')

index_m = (uint8_t)(GetSize() - (uint8_t)1 + index_m) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]

index_m = (uint8_t)(index_m + (uint16_t)1) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 732: loss of sign (assignment) ('int' to 'uint8_t' (aka 'unsigned char')

index_m = (uint8_t)(GetSize() - (uint16_t)1 + index_m) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]

...C 真痛苦!

有什么快速解决方法?


看完评论我也试了下没成功

     index_m = (uint8_t)(index_m + (uint32_t)1) % GetSize(); // works

index_m = (uint8_t)(GetSize() - (uint32_t)1 + index_m) % GetSize(); // info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]

这让我摆脱了符号/无符号混合问题,但这个“运算符‘-’后跟运算符‘+’”仍然很奇怪!

最佳答案

What's the quick fix for this?

最简单的是:

 index_m = (index_m + 1U) % GetSize(); // this one works

ok for incrementation but the problem is with the decrementation...

index_m = (GetSize() - 1U + index_m) % GetSize();// info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]

请注意,这只是一条信息消息;不是警告。但无论如何,缺少括号的解决方案是添加括号:

index_m = ((GetSize() - 1U) + index_m) % GetSize();

或者,显然将操作顺序更改为 (GetSize() + index_m - 1U),如评论中所见

关于c++ - 混合 C 和 C++ 代码的静态分析怪异符号行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com