简体   繁体   中英

why *foo ++= *++foo may be undefined?

it should set the current character to next character. For example:

while( *foo ) { 
 if(baa(*foo)) *foo++ = *++foo;
  foo++;
}

But I get the following errors:

error: operation on ‘foo’ may be undefined [-Werror=sequence-point]
cc1: all warnings being treated as errors

Can anyone explain why that? that isn't valid C syntax?

You're incrementing foo on both sides of the assignment, with no sequence points in between. That's not allowed; you can only modify a value once between sequence points.

Let's take a closer look at this expression:

*foo++ = *++foo

*foo++ evaluates as *(foo++) (postfix ++ has higher precedence than unary * ); you take the current value of foo and dereference it, and advance foo as a side effect. *++foo evaluates as *(++foo) (both unary * and ++ have the same precedence, so they are applied left-to-right); you take the value of foo + 1 , dereference the result, and then advance foo again as a side effect. Then you assign the result of the second expression to the first.

The problem is that the exact order in which all of those side effects are applied (assignment, postincrement, and preincrement) is unspecified ; the compiler is free to reorder those operations as it sees fit. Because of this, expressions of the form x++ = ++x will give different results for different compilers, or for the same compiler with different compiler settings, or even based on the surrounding code.

The language standard explicitly calls this out as undefined behavior so that compiler implementors are free to handle the situation any way they see fit, with no requirement to try and do the "right thing" (whatever the "right thing" may be). GCC obviously issues a diagnostic in this case, but they don't have to. For one thing, not all cases are so easy to detect as this. Imagine a function like

void bar (int *a, int *b)
{
  *a++ = *++b;
}

Is this a problem? Only if a and b point to the same thing, but if the caller is in a separate translation unit, there's no way to know that at compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM