Behaviour of post increment/decrement operator

int i = 1;
i = ++i;
System.out.println( i ); //output is 2
i = i++;
System.out.println( i ); // output is 2, WHY?

Well, it seems that you didn't get the point at all.
I know how to do the increment operation. What I
intended to know is the behavior in this scenario.
And you got that in reply 2.I assumed the answer to be that. but i was only trying to be sure.
I know that such codes r not in common use and they are meaningless too, but such codes do come up in various quizzes, etc. to test ur knowledge. we always learn WHAT not to do, but we seldom try to know WHY not to do it. in our endeavor to learn advanced topics we tend to ignore the basics.
Coming back to the original code can someone tell me whether this is a well defined behavior unlike c/c++ where the behavior of such codes are undefined. as far as i know java is a strongly typed language, where ambiguities have been eliminated (believe i am not wrong on this). Can i expect the same results on all compilers??
and i hope that the forum behaves in a sane manner in future. Instead of blatantly dismissing a post, let people give reasons for it.
Thanks

Similar Messages

  • CVI 2013 compiler: increment / decrement operator evaluation

    I'm looking at pulling an old project forward to CVI 2013, but have hit a challenge, which is documented as follows:
    "In assignment, the value of the right operand is evaluated before an array indexing is performed in the left operand. Expressions such as a[i] = i++; will evaluate differently in LabWindows/CVI 2013 when compared with previous versions."
    (There is a somewhat related thread here to do with the order that function arguments are evaluated.)
    This change in evaluation order is shocking to me. I assume there is some C history behind it, and I'm not going to be able to change that.
    So, my question is: What is the easiest way to find all places in my code where this could affect me? I have ~75,000 lines of legacy code. Perhaps some regex magic?
    Thanks,
    Ian
    Solved!
    Go to Solution.

    You can try to compile your code with sequence point checking. CVI compiler doesnot seems to know that.
    But maybe lastest version of clang and/or gcc can help there. Be sure to compile with and without optimization, some warning messages depend on this.
    ( try -Wsequence-point on cmd line or  something like #pragma clang diagnostic warning "-Wsequence-point" in source code)
    Better but harder(i think) sollution can be to use some MISRA-C checker, they should detect this but maybe they give you too much warnings about all the unspecified and undefined behaviours.
    Some list is on (section analyzers): https://www.securecoding.cert.org/confluence/display/seccode/CERT+C+Coding+Standard
    I do not use any of them so i cannot reccomend one.

  • Post Increment Operator Question

    I had written a small program to test the working of Post increment operator.
    public static void main(String[] args)
         int a = 4;
         a = a++;
         System.out.println ( a );
    I expected the output to be '5', but the output given is '4'.
    Can anyone tell me to how this works in Java ?

    There is a big difference between a++ and ++a.
    a++ means increment a AFTER you have performed the line.
    ++a mean increment a BEFORE you perform the line.
    class Test
    public static void main(String[] args)
    int a = 4;
    a = ++a; //returns a = 5
    // a = a++; //returns a = 4
    //a++; //returns a = 5
    //++a; //returns a = 5
    System.out.println ( a );
    }

  • Why we use increment or decrement operator

    Hi. I want to know that is there any advantage of using the increment or the decrement operator. Does it makes the code a bit faster to run, etc.
    Actually i find these operators to be a bit confusing. so want to ask why should we use them and when.
    Thanks.

    baftos wrote:
    I am not kidding. It's a personal opinion that may be wrong.
    I'll tell you why I think what I think and I would be glad to change my opinion if someone shows me the light.
    Those operators are just syntactic sugar.So is a bunch of other stuff in Java (imports and the foreach loop, for example). Syntactic sugar is a good thing when it makes common idioms more compact, or stand out as what they are, as opposed to just another instance of a more general case. (Although I don't really consider these syntactic sugar.)
    Everything they do can be done otherwise more clearly.I disagree. "Increment" is an all-pervasive operation in programming. Sure, it can be done as just another case of x = x + something, where in this case something happens to be one, but in my opinion, that's not as descriptive. x++ is compact, concise, easy to read, and stands out clearly as "increment x".
    Without them the language would be just simpler.
    No more riddles about i=i++, Any language feature can be abused or misunderstood. That in itself is not a valid argument against including it. This misunderstanding is very easy to correct. It's on the same scale with redeclaring a member as a local and then wondering why you're getting NPE when trying to use the member elsewhere. It's not even in the same league as things like operator overloading or MI of implementation.
    why n=i+1 requires cast, but not n=++i, the relation between boxing and the ternary etc.Again, these are little quirks, corner cases that cause some minor confusion but not major problems. To me this kind of stuff is no different than stuff like using compile-time constants for case conditions or to assign a wider integer type to a narrow one without a cast. It's stuff that makes the language easier to read and write for a lot of common use cases, at the cost of some minor complexity in the corners.
    They were retained from C, while other things were discardedWhich is neither an argument for nor against them.
    Edited by: jverd on Oct 31, 2009 9:37 AM

  • Increment decrement visible property

    It would appear that (in LV 2012 SP1) the simple numeric control from the Classic palette shows following behaviour when accessing via VI Server:
    Class Name = "Digital"
    Increment / Decrement Visible = Error, property not found
    ?? What ??
    It appears that these controls, although being a member of the "Digital" VI Server class do not honour the interface of the class of controls it belongs to.  Is this by design or is it a bug?
    This caused me some headaches in the last 24 hours.  I was not aware that "Increment / Decrement Visible?" was one of those properties which may or may not be present (Like a valid "Caption" reference when a Caption is not visible.  At least here we have a check with "Has Caption?".
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

    Error 5014? 4150? I'll get there eventually.
    So it's kind of expected then. Seems a bit weird that a plain "ByVal" property is sometimes not supported.  I knew that was the case with References (Text labels, Scales etc.) but not with these kinds of properties.
    I live and I learn (and get lots of error codes wrong).
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

  • Error while Posting to all operative areas

    hi,
    while posting to all operative areas in TBB1 am getting the following error
    "No accounting rule despite posting to general ledger ERP" for valuation area 002. Whereas no error for operative valuation area 001.
    Please help.

    Hi Sur,
    the long text SAP note 922332 explains what to do in this case: is there an accounting principle assigned to all of the relevant valuation areas for the accounting code in IMG under  'Assign Accounting Codes and Valuation Areas'?
    Best regards,
    Marie
    SAP TRM

  • Can I set the Increment/​Decrement to not visible by default?

    The Increment/Decrement attachment to ALL the Numeric controls is a nuisance.  Give me a palette that does not have the Increment/Decrement visible by default and my life will be MUCH better.  I would not mind clicking on a check box if it was needed. 
    How can I make it NOT visible by default?
    Solved!
    Go to Solution.

    Thanks,
    It took me a while but I got it done!  I use the Modern style so it is not that easy as it would be with Silver.  I just think Silver looks 'Bloated'.
    Now I don't have to turn off that check mark everytime i place a numeric control!  YEA

  • Pre/Post increment query

    I have a query regarding Pre/Post increment.
    The following code:
    int x = 0;
    int y = 0;
    x += y++;
    System.out.println("x = " + x);
    System.out.println("y = " + y);
    Produces the following output:
    x = 0
    y = 1
    (Value of y is assigned to x, y is then post incremented).
    This makes sense to me. However the following code,
    the value of x does not get incremented. Can someone
    explain this to me?
    The following code:
    int x = 0;
    x += x++;
    System.out.println("x = " + x);
    Produces the following output:
    x = 0
    (Value of x is assigned to x, then x does not get post incremented??).

    I code with the mind set of "If the code is not self explanatory or obvious, then
    it's too confusing and should be avoided".
    I am studying for the Java Programmer Certification exam, so this query was more
    to try and understand why the output did not match what I had expected.
    So
    x += x++;
    is the same as (where x' refers to the original value of x)
    x = (x) + (x++);
    which is then executed in the following order:
    x = x++; //(x = x + 1) post incrementation
    x = x' + x'; //(x = 0 + 0) evalutation of the assignment
    Thanks for all the responses!!

  • Post increment problem. please help to solve it

    public class test {
    public static void main(String args[])
         int i=10;
         i=i++;
         System.out.println(i); // value of i is 10 why
    }

    Mostafa.Hashem wrote:
    Absofuckinglutely NOT !
    1) Save current value of x. That is, 1. This is the value of the expression "x++".
    2) Increment x. x is now 2. We have now completed x++
    3) Assign value from step 1 into y.i wonder how small point like this takes all that time.
    Mr Jverd,
    the difference between prefix increment and the postfix increment is :
    IN PREFIX INCREMENT THE ASSIGNMENT OF EXPRESSION DONE FIRST THEN THE INCREMENT.
    IN POSTFIX INCREMENT THE INCREMENT DONE BEFORE THE ASSIGNMENT.Wrong.
    ++x and x++ are both expressions. They have a value and a side effect.
    In pre-increment (++x) the increment is done before the expression is evaluated. The value of the expression is the new value of x.
    In post-increment (x++) the increment is done after the expression is evaluated. The value of the epxression is the original value of x.
    In both cases
    y = ++x;
    y = x++;
    The right-hand side is evaulated completely before the assignment to y is done. In fact, in ALL java assignment statements, the RHS is evaluated completely before assigning anything to the LHS.
    y = ++x;
    is equivalent to
    x +=1;
    y = x;
    y = x++;
    is equivalent to
    tmp = x;
    x += 1;
    y = tmp;

  • Post increment question

    I was looking at this puzzle question:
    public class Assignment {
    public static void main(String[] a) throws Exception {
    int tricky = 0;
    for (int i = 0; i < 3; i++)
    tricky += tricky++;
    System.out.println(tricky);
    tricky is 0. How come the post increment in this case does nothing?

    I was looking at this puzzle question:
    public class Assignment {
    public static void main(String[] a) throws Exception
    int tricky = 0;
    for (int i = 0; i < 3; i++)
    tricky += tricky++;
    System.out.println(tricky);
    tricky is 0. How come the post increment in this case
    does nothing?
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=753569

  • Non operating expenses can only be posted to non operating cost centers

    Hi ,
    Where do we defien the relation/validation " Non operating expenses can only be posted to non operating cost centers" in SPRO ? Is it a part of configuration or validation ?
    Regards,
    Pradeepa

    Hi,
    In my knowledge, it is not configuration issue. Write validation for this. At the time of posting of Non operating expenses, you have to select non operating cost centers. If  you select other cost center system will prompt error message according to your validation.
    Thanks
    Chandra

  • Comic project part 2: IB Action? to increment/decrement displayed jpeg?

    In part 2 of the neverending saga of one man attempting to create an iphone wrapper for his comic, I take the array constructed in part 1, and look for a method to hook forward and backward buttons to the procedure that will increment/decrement(i.e. step backward and forward between them)the number of the jpeg that is displayed. Anyone who feels like they know it all, please feel free! In part 3, stay tuned, as I beg for assistance in making the heretofore portrait application, autorotateable for those artists who simply Must have landscape images instead!

    It is easy to do. In your controller keep a current page variable that tracks the image on display. The event handler needs only increment/decrement this variable and fetch the appropriate image from your array.

  • Post increment operator i++

    I can't seem to figure out why the following is outputting 2,2,3 and not 2,3,4. Having searched the Java Language Spec and reading ... (http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#39438)
    ... it is still not clear. The key line probably is "The value of the postfix increment expression is the value of the variable before the new value is stored." I still think that the second output should have been 3 and not 2. Could someone explain this to me? Thanks.
    Here is the code that I tried:
    int i;
    i = 2;
    System.out.println(i);
    i = i++; // the line which I don't understand
    System.out.println(i);
    i++;
    System.out.println(i);

    The key is to understand the difference between the
    value of the expression and the value of the
    variable.
    i = i++;What that particular bit of devil-spawn does is
    this:
    1) Get the current value of i. The value of the
    postfix increment expression is the value of the
    variable before the new value is stored. So we
    have to get the "before it's incremented" value. This
    is the value of the expression i++.
    2) Increment i. This doesn't alter the value of the
    expression that was obtained in step 1.
    3) Take the value of the expression that was
    retrieved in step 1 (the value of i before being
    incremented) and stuff it into i.
    If you had int i = 2;
    int j;
    j = i++; Would you expect j to be 2 or 3? It will be 2. And
    the same reason that j is 2 here makes i 2 if you put
    i on the left of the equals.When the expression is "i = i + 1" compiled, it should be divided into two sub expressions :
    1.) i = i; //As postfix defination says use value first and then increment
    2)i = i + 1//Increment i;
    so, accordingly, the value of i after first step should be 0 and then after second step it is 1(C,C++ behaviour).
    so, the statement i = i++ must result into the value 1 for i, not 0.
    even in C#.net the value of i is 0 after the execution of above statement.

  • Strange Post-Increment/Assignment Behaviour

    I have a problem understanding the code snippet below :
    public class trythis {
         public static void main(String args[])
              int i = 0;
              i = i++; // ??
              System.out.println(i);
    I thought that the output of this program should be 1, but when I ran the progam it gave the output 0.
    I don't understand the reason. Can anyone help me understand the logic behind this?
    Thanks.

    OK so here is an elaborate explanation:
    This is an assignment:
    i = i++;
    According to the Java Language Specification �15.26.1 the first thing that happens is that the left hand side is evaluated. It clearly evaluates to the variable i. The next thing that happens is that the right hand side (i++) is evaluated. So let's look at that...
    This is a postfix increment expression:
    i++
    According to the Java Language Specification �15.14.1 the following happens: The variable is evaluated (this is i which is 0), 1 is added to the variable value (giving a value of 1) and the result is stored in the variable (making i=1). The value of the whole expression (i++) is the value of the variable before it was incremented. The variable i had the value 0 before it was incremented so the value of the right hand side is 0. Now back to the assignment...
    The right hand side has now evaluated to 0. The value of the right hand side is then stored in the variable denoted by the left hand side (i). So after the assignment i has a value of 0.
    S&oslash;ren

  • Decrement operator precedence confusion

    Here is the snippet from a book:
    int y = 5;
    int result = y-- * 3 / --y;
    System.out.println("y = " + y);
    System.out.println("result = " + result);Assuming increment and decrement have highest precedence, I don't get the explanation:
    Order of operations dictates that the multiplication is evaluated first(WHY???). The valueof y is 5, so 5 * 3 is 15. The multiplication is done, so the post - decrement occurs and y
    becomes 4. Now the division is evaluated and y is pre - decremented to 3 before the division,
    resulting in 15 / 3 , which is 5. The output of this code is:
    y = 3
    result = 5
    Any comments would be appreciated.

    AntShay wrote:
    Oh, no!
    There's something more I don't get :)
    Why is 5 *** 3 takes place instead of 4 *** 3? Pre-decrement has higher precedence, hasn't it?
    So, from my point of view this should work as follow (please correct me where I'm wrong):
    int y = 5;
    int result = y-- *** 3 / --y;
    1) y-- gets evaluated (y=4 now)
    2) --y gets evaluated (y=3)
    3) 3 *** 3 = 9
    4) 9/3 = 3I don't know if pre-dec has higher precedence than mult, but even if it does, that doesn't matter. That's not what precedence means. It doesn't mean you jump around and do those operations first. I just means "This is where the implied parentheses go." The only affect it has on order of evaluation is when you have to evaluate something inside the implied parens first to get an operand for the next operation.
    3 + 4 * 5In the above, mult has higher precedence than add, so it's equivalent to
    3 + (4 * 5)It doesn't mean "first do all multiplications, then all adds." It means the implied parens are as above.
    So:
    1. evaluate 3
    2. evaluate the RH operand of +++
    2.1 evaluate 4
    2.2 valuate 5
    2.3 multiply 4 *** 5 --> 20
    3. evaluate 3 +++ 20
    So we did the mult before the add because we had to in order to get the value of the RHS operand of the plus. Indirectly it's because mult has higher precedence, but that's just a consequence of the implied parens, and we still evaluated the 3 before doing the mult. We did NOT do "all mults first, then all adds."
    Similarly, if it had been
    2 + 3 + 4 * 5we would eval 2, then eval 3, then add, then eval the RHS of the second plus operator, which means we'd have to eval 4 *** 5. Note that we do NOT eval 4 *** 5 as the very first step before all adds.
    Now, say pre-dec has higher precedence than mult. It may, it may not, I don't know and I don't care. It doesn't matter here, but let's say it does.
    y-- * 3 / --yis the same as
    (y--) * 3 / (--y)Operands are still evaluated L to R. We don't just jump around.
    1. Evaluate y--
    1.1 value of expression is 5
    1.2 decrement y to 4
    2. Evaluate 3.
    3. Multiply #1 *** #2 --> 5 *** 3 = 15
    4. Evaluate --y
    4.1 decrement y
    4.2 valueof expression is 3
    5. evaluate #3 / #4 --> 15 / 3 = 5
    Edited by: jverd on Feb 12, 2010 11:54 AM
    Edited by: jverd on Feb 12, 2010 11:56 AM

Maybe you are looking for