Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: question about incrementing variables

  1. #1
    Junior Member
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default question about incrementing variables

    Hello all,
    I have perhaps one silly question...
    when i compile code :
    int k = 5; 
    k = ++k + k++;
    System.out.println(k);

    I get output 12 instead of 13 (as i would if I use c++ compiler). I know this type of coding is "wrong" but i just wonder why do I get that kind of output I understand how does gcc do this... first increment k to 6, then add those two k's (6+6) and put it on memory location of the k, and after that line is executed, just before it fetch new instruction k will be incremented by one so it will be 13 and if I would do something like "cout << k" in the next line I would get 13 in the output...

    but here I'm a bit confused and any explanation is very useful


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: question about incrementing variables

    k = ++k + k++;
    Anyone that coded that way is trying to confuse other programmers and should be fired.
    Code should be written in an easy to understand way or with good comments fully explaining what it is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: question about incrementing variables

    I know
    that's why I said it's wrong to do it like this
    I just wonder how does java compiler handles this situation with ++k and k++ (because stack memory is not in the physical memory but in the stack memory of the virtual machine)

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: question about incrementing variables

    To see what the compiler generates, look at the byte code, The javap command will list it.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: question about incrementing variables

    It seems that there are two times incrementing... but both of them is before adding... after adding two integers, it stores value and after that there's no increment...
    now i'm just more confused



    btw when i look at byte code of similar code
    		int k = 5; 
    	//	k = ++k + k++;
    		k = ++k + ++k;
    		System.out.println(k);
    it's the same just order of two instructions are changed (load and increment) but this code gives me output 13 (as first one should) but if i look at this with any logic this one should say 14....


    Am I wrong if i think that those two "k" on the right side of = are not on the same memory location ?! I don't see any other explanation for this...
    Last edited by yeKciM; March 30th, 2013 at 04:12 PM. Reason: tried something...

  6. #6
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: question about incrementing variables

    int k = 5; 
    k = ++k + k++;
    System.out.println(k);

    I'd expect 12 not 13 to be printed.

    Those ++ things are operators and they form expressions. It's best to keep these two roles distinct and recognise that operators have effects on the value of variables while expressions have values that might go on to play a role in larger expressions.

    ++k: the effect is to increment k, the value is the incremented value of k
    k++: the effect is to increment k, the value is the original value of k

    So, working left to right (as Java does) we get

    ++k
    This increments k which is now 6. It has the value 6.

    k++
    This increments k which is now 7. It has the value 6.

    ++k + k++
    This has the value 12 ie the values of the two terms added together

    k = ++k + k++
    This assigns 12 to k. Ie it assigns the value of the right hand side to k

  7. The Following User Says Thank You to pbrockway2 For This Useful Post:

    yeKciM (March 30th, 2013)

  8. #7
    Junior Member
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: question about incrementing variables

    Thanks
    I know it's stupidity to write somethig like that code I wrote but i just wondered since if i do

    someArray[i++]

    I get ith element and "i" will be i+1 after that line. But when i do :

    someArray[++i]

    I get i+1 element from that array...

    That's why thought it will be 6 + 6 = 12 and after that increment by 1

    Thanks very much

  9. #8
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: question about incrementing variables

    I'm glad it helped.

    Personally I find it easier to think in terms of an operator's effect and the resulting expression's value rather than trying to figure out the particular ordering of events.

    Java is more straightforward (I think) in this regard than C. For example the following Java code admits the same sort of analysis (although it probably falls into Norm's category of Code That Should Not Be Written):

    import java.util.Arrays;
     
    public class ArrayEg {
        public static void main(String[] args) {
            int[] arr = new int[5];
            int i = 2;
            arr[i] = i++;
            // arr[i] = ++i;
            System.out.println(Arrays.toString(arr));
            System.out.println("i=" + i);        
        }
    }

    (Predictions of what either form will do is left as an exercise.)

    K&R thought that the ambiguous (in C) "arr[i] = i++;" was unspecified. Later standardisers got tough and made it undefined. Java just does what Java always does: works through the two terms left to right, and considers the second term (i++) to do something but also to have a value.

Similar Threads

  1. [SOLVED] Help with the incrementing in a For loop
    By gabie1121 in forum Loops & Control Statements
    Replies: 2
    Last Post: October 26th, 2012, 11:55 AM
  2. Differences between local variables and instance variables
    By rob17 in forum Java Theory & Questions
    Replies: 2
    Last Post: March 6th, 2012, 08:34 PM
  3. Instance Variables and local variables difference
    By dcwang3 in forum Java Theory & Questions
    Replies: 3
    Last Post: October 31st, 2011, 06:33 AM
  4. Incrementing button by 1
    By joshft91 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: March 1st, 2011, 10:45 AM
  5. Java Question Need Help Restarting the Values of Variables from Random Numbers So Out
    By JavaStudent1990 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 24th, 2010, 02:25 PM