[英]Modulo arithmetic with signed integers undefined behavior in c?
Having read all answers and comments in Should you always use 'int' for numbers in C, even if they are non-negative? 阅读了中的所有答案和注释后,即使C是非负数,您是否也应该始终对C中的数字使用'int'吗? I'm still not sure what to do in the following situation. 我仍然不确定在以下情况下该怎么办。
Two remote devices are counting events at their respective location. 两个远程设备正在其各自位置计数事件。 They regularly report the counter readings to a PC where a feedback algorithm somehow keeps the difference of the counter readings within bounds. 他们定期将计数器读数报告给PC,在PC上通过反馈算法将计数器读数的差异保持在一定范围内。 The sequences of events are endless so that the readings are reported modulo 2^n. 事件的序列是无止境的,因此读数以2 ^ n为模数报告。 For modulo arithmetic unsigned integers are suggested. 对于模算术,建议使用无符号整数。 The difference, however, may well become negative. 但是,这种差异可能会变成负面的。 Casting the readings to signed integers before calculating the difference works fine on the platform I tested it on (that is, I get the differences modulo 2^n with values small in magnitude). 在计算差异之前,将读数转换为有符号整数可以在我测试它的平台上正常工作(也就是说,我得到的差异取模2 ^ n且幅值较小)。 Declaring the readings as signed already in the interface yields elegant code. 将读数声明为已经在接口中签名,会产生精美的代码。 However, the code shall be portable. 但是,该代码应是可移植的。 Shall I take the UB warning seriously? 我应该认真对待UB警告吗?
Shall I take the UB warning seriously? 我应该认真对待UB警告吗?
If you don't want your compiler or CPU play tricks on you, your code should be UB-free. 如果您不希望编译器或CPU玩弄花样,则您的代码应不含UB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.