简体   繁体   English

带符号整数的模运算在C中未定义行为?

[英]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.

相关问题 哪些“C”实现不实现有符号整数的模运算? - Which “C” implementation(s) do not implement modulo arithmetic for signed integers? 为什么对于负整数,C 和 Ruby 之间的模运算符 (%) 的行为不同? - Why is the behavior of the modulo operator (%) different between C and Ruby for negative integers? 有符号整数的未定义行为和 Apple 安全编码指南 - Signed integers' undefined behavior and Apple Secure Coding Guide C:在计算中使用无符号操作数时如何最好地处理无符号整数模算术(“环绕”) - C: How to best handle unsigned integers modulo arithmetic (“wrap-around”) when using unsigned operands in calculations 两个联合的算法,未定义的行为? - Arithmetic for two unions, undefined behavior? C指针算术奇怪行为 - C Pointer Arithmetic Strange Behavior 为什么对无符号字符的算术运算将它们提升为有符号整数? - Why do arithmetic operations on unsigned chars promote them to signed integers? 这种用法中的指针算术是否会导致未定义的行为 - Does the pointer arithmetic in this usage cause undefined behavior 是对空指针未定义行为执行算术? - Is performing arithmetic on a null pointer undefined behavior? 动态分配的内存上的指针算法具有未定义的行为 - Undefined behavior with pointer arithmetic on dynamically allocated memory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM