Frage

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

War es hilfreich?

Lösung

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++.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top