« Mifos at OSCON 2008


May
1

Mayday Programming Brain Teaser

Posted by adam in Interesting

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 Responses to “Mayday Programming Brain Teaser”

  1. Added by Steven on May 1st, 2008 at 5:30 pm

    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. Added by Jason on May 1st, 2008 at 8:17 pm

    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!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> , and <pre> should work, too. I usually put code examples in both <blockquote> and <pre>. Backslashes must be escaped (with another backslash). Angle brackets, etc. must be replaced with HTML-entities, even in code examples. For example: &lt; and &gt; for < and >.

Comment