Mayday Programming Brain Teaser

Thanks to Sam for the idea.

int k = 0;
k = k++;

After both lines execute, what is k equal to?

Apparently, the answer depends on a number of things. In Java, k is 0. In C, it may be 0 or 1 depending on your compiler!

Bonus points if you can explain why.

2 thoughts on “Mayday Programming Brain Teaser”

  1. The system/application admin says:

    Because some parsers see ++ as a sequential step to perform after the items before it.

    “the variable k is equal to the variable k. now increment k by one.”

    In some languages this can be solved by writing the code like this:

    k = ++k;

    Which translates to “the variable k is equal to the incremented value of k.”

    Or I could be completely wrong… :-)

  2. I would guess that the result in C was dependent on how closely the compiler follows operator precedence/binding.

    The postfix increment operator “++” is at the top of the precedence chart where direct assignment “=” is almost at the bottom.

    Wouldn’t CPP turn it into:

    k = (k++)

    and not:

    k = k;
    k++;

    ??

    Then I found this:

    “Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done.”

    I couldn’t locate a copy of the ANSI C standard in the 5 min. I spent looking…

    YMMV. Darn!

Comments are closed.