Turbo C++ and GCC (using codeblocks on windows) evaluate the same ternary expression differently

StackOverflow https://stackoverflow.com/questions/14506895

문제

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