#include <stdio.h>
int main(void)
{
int i = 0;
i = i++ + ++i;
printf("%d\n", i); // 3
i = 1;
i = (i++);
printf("%d\n", i); // 2 Should be 1, no ?
volatile int u = 0;
u = u++ + ++u;
printf("%d\n", u); // 1
u = 1;
u = (u++);
printf("%d\n", u); // 2 Should also be one, no ?
register int v = 0;
v = v++ + ++v;
printf("%d\n", v); // 3 (Should be the …Run Code Online (Sandbox Code Playgroud) c increment operator-precedence undefined-behavior sequence-points
我读了几个关于未定义行为和序列点的非常好的答案(例如未定义的行为和序列点),我明白了
int i = 1;
a = i + i++; //this is undefined behaviour
Run Code Online (Sandbox Code Playgroud)
根据C++标准,是未定义的代码.但是,未定义的行为背后的深层原因是什么?是否足以使其成为未指明的行为?正常的论点是,通过几个序列点,C++编译器可以更好地针对不同的体系结构进行优化,但是不会让它未指定允许这些优化吗?在
a = foo(bar(1), bar(2)); //this is unspecified behaviour
Run Code Online (Sandbox Code Playgroud)
编译器也可以优化,并且它不是未定义的行为.在第一个例子中,似乎很清楚,a是2或3,所以语义似乎对我来说很清楚.我希望有一个推理,为什么有些东西是未指定的,有些是未定义的.
我正在尝试编写一个检查通过a的函数char* a[],并且经常最终使用类似的东西
if(a[i] == 'x'){
i++;
//...
}
Run Code Online (Sandbox Code Playgroud)
现在我真的想改变a[i++]它,但它似乎没有用.
题:
我在这里做错了什么,还是有一个干净的选择来避免i++?
注意:目前函数中我的13行中有3行i++,这使它看起来比实际大得多.