Search code examples
coldfusionternary-operatorcfmlcoldfusion-2016

Variable in ternary operator never increments


q.rel can be either 1, 2, or 3

for (q in qry) {

    pCode = (q.rel NEQ 3 ? q.rel 
       : pCode GTE 3 ? pCode++ : 3);

    ...
}

If there are a bunch of q.rel is 3 in a row, pCode is supposed to increment, but it only shows 3.

Note that there is no initial setting of pCode anywhere else. This is complete.


Solution

  • That's how postfix incrementing works. I will demonstrate the order of operations with assembler and use registers to avoid confusion about a temporary variable (that actually doesn't exist).

    These instructions (postfix increment):

    x = 0;
    x = x++;
    // x is still 0
    

    translate to:

    mov eax, 0   ; x = 0
    mov ebx, eax ; x assignment on the right-hand side
    mov eax, ebx ; x = x
    inc ebx      ; x++
    

    "x" was incremented after the assignment was executed and thus the value never changed.

    Now these instructions (prefix increment):

    x = 0;
    x = ++x;
    // x is now 1
    

    translate to:

    mov eax, 0   ; x = 0
    mov ebx, eax ; x assignment on the right-hand side
    inc ebx      ; ++x
    mov eax, ebx ; x = x
    

    "x" was incremented before the assignment was executed and thus the value changed.

    That's pretty much how every programming language handles it. This is not related to the ternary operator at all.