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