I have this expression

(*p % 3 != 0) ? *p = (*p) + 1 : *p = (*p) + 2;

In Turbo C++ it evaluates to 14 if *p is 11 and to 35 if *p is 33

In GCC (Windows) it evaluates to 12 and 35 respectively which is what is expected

It works fine when parenthesized to the following format:

(*p % 3 != 0) ? (*p = (*p) + 1) : (*p = (*p) + 2); 

Is there any explanation for this difference? I'm guessing it comes down to differences in the precedence order used by the compilers but cannot pinpoint the root cause

有帮助吗?

解决方案

The ternary conditional operator is different in C and in C++. The expression a ? b : c = d is parsed...

  • as (a ? b : c) = d in C, and

  • as a ? b : (c = d) in C++.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top