我一直在从事嵌入式 C 项目,并且我找到了代码:
x = ++x % 5;
现在,首先,一个表达式中的变量 x 有 2 个副作用运算符:赋值运算符和前缀增量运算符。
根据C99标准(ISO/IEC 9899:TC3):
第 6.5 节表达式
- Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
这应该被视为未定义的行为,但我在实践中还没有成功证明这一点。 在 Windows(mingw32-gcc、msvc)和 Linux 上尝试了一些编译器:
gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
Ubuntu 18.04 4.15.0-36-generic
所以我的问题是,这在嵌入式中是否被认为是未定义的行为,并且在嵌入式中使用它是否安全?
最佳答案
如果我在 gcc
上编译代码,它会显示我
source_file.c: In function ‘main’: source_file.c:8:7: warning: operation on ‘x’ may be undefined [-Wsequence-point] x = ++x % 5; ^
这是第一个证据,证明这可能是 UB。
除此之外,增量(写操作,又名存储值修改)和赋值(再次,写操作,又名存储值修改)发生时之间没有序列点,所以这是未定义的行为。
也就是说,只需写
x = (x + 1) % 5 ;
更好,更易读,并且 lessens the threat on your life .
关于c - 这是否被认为是未定义行为 x =++x % 5;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428119/