From: bouncer@dev.null   
      
   James K. Lowden wrote:   
      
   > On Thu, 17 May 2012 00:13:35 -0700 (PDT)   
   > ravinder thakur wrote:   
   >   
   >> int x = 10;   
   >> x = x++;   
   >>   
   >> I expect value of x to be 10 after the second assignment   
   >   
   > Ask yourself this: Why do you think x should be 10?   
   >   
   > If you want your expectation to match what the machine does, you   
   > cannot use intuition. Be the compiler. Think like a machine.   
   >   
   >> x = x++;   
   >   
   > Consider the steps:   
   >   
   > A. assign x to itself   
   > B. increment x   
   >   
   > Even if you don't know which order they'll occur in, neither one ends   
   > with x equal to 10.   
      
   Think like a machine? OK, I'll try. What I see is an assignment   
   statement. Such a statement has a left hand side ('x' here) and a   
   right hand side ('x++'). So here I go:   
      
   (1) evaluate the left hand side. The result is an lvalue referring to   
   the variable x.   
      
   (2) evaluate the right hand side. The result is an rvalue reflecting   
   the old value of x (10). As a side effect, x is incremented.   
      
   (3) Assign the result of (2) to the result of (1). Voila: x   
   becomes 10.   
      
   I would love a language rule that says that (1) must occur before (2),   
   but in this case, that wouldn't matter. Here, what matters is a rule   
   that says that (3) will occur after both (1) and (2) have completed.   
   In any case, the machine will do what the compiler tells it to do.   
      
   I know C++ currently does not have such rules, but that doesn't mean   
   they wouldn't be useful. Until it does, questions like this one will   
   keep popping up.   
      
   - Wil   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|