Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

post-increment/pre-increment blues

by wil (Priest)
on Jun 18, 2002 at 08:49 UTC ( [id://175306]=perlmeditation: print w/replies, xml ) Need Help??

[ This post is meant to be a little bit of fun, and educational too. Skip if you want. ]

Without cheating (too much), can you tell what each print statement will print and the value of $i after each print?

Bonus points for those who explain their answers.

my $i = 0; print ++$i + 1; print $i++ + 1; print $i + $i++; print ++$i + ++$i; print ++$i + $i++ + 1;


- wil

Replies are listed 'Best First'.
Re: post-increment/pre-increment blues
by ariels (Curate) on Jun 18, 2002 at 09:48 UTC
    my $i = 0;
    1. "print ++$i + 1;" -- increments and prints 2.
    2. "print $i++ + 1;" -- prints 2 and increments.
    3. "print $i + $i++;" -- isn't documented to do anything particularly useful in Perl. "perl" might have some particular behaviour, but it is in no way guaranteed in any way or form. Other languages have multiple implementations; that makes separating implementation peculiarities from the language definition easier.

      In fact, the equivalent C code "i+(i++)" is undefined behaviour in ISO C: the compiler is allowed to return (assuming the variable starts off with 2) any value, or write code to format your computer's disks, or write code to format everybody else's computers' disks, or cause daemons to fly out of your nose.

    4. "print ++$i + ++$i;" -- You guessed it! Same as above!
    5. "print ++$i + $i++ + 1;" -- Yup. Same again.

    For related fun, try the various "$i=$i++" (also undefined).

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: post-increment/pre-increment blues
by Zaxo (Archbishop) on Jun 18, 2002 at 09:43 UTC
    2 $i == 11+1 
    2 $i == 2,1+1 
    5 $i == 33+2, tricky, post-- precedence
    10 $i == 55+5, It's not what I expected.
    14 $i == 77+6+1, nor this
    Apparantly pre-increment returns an alias.

    ++wil, you taught me something :)

    After Compline,
    Zaxo

      I should probably point out that wil's post and explanation are not his own and are blatantly copied from: http://gossamer-threads.com/perl/gforum/gforum.cgi?post=199967; Your da man Wil!
Re: post-increment/pre-increment blues
by rinceWind (Monsignor) on Jun 18, 2002 at 10:37 UTC
    The subject of autoincrement and side effects was discussed in this thread. Although we are not dealing with lvalue assignment to $i, as ariels has said, the result of the calculation is defined to be ambiguous in the C standard, and I guess the same is true of Perl. Hence you can get different results depending on platform, version and what mood the optimiser is feeling in :).
      print ++$i + $i++ + 1;

      Entering this line with i==5 prints (6+7+1) or (7+6+1). Sooo ++ has higher precedence than +. Certainly fun, but really not so hard to figure out why 14, eh?

        ++ has higher precedence than +, but that's irrelevant. Precedence only determines how things are parsed. It does not determine the order of evaluation.

        As pointed out to people before, the value of the expression ++$i + $i++ + 1 is undefined. Any reasoning about what the value would be is a futile exercise. Any answer is as good (or wrong) as any other.

        Abigail

Re: post-increment/pre-increment blues
by PetaMem (Priest) on Jun 18, 2002 at 09:50 UTC
    Hi,

    first off, i can't explain my answers for everything including and after the 3rd print statement. My guess was:

    my $i = 0; print ++$i + 1," I: $i\n"; # guess 2 print $i++ + 1," I: $i\n"; # guess 2 print $i + $i++," I: $i\n"; # guess 4 print ++$i + ++$i," I: $i\n"; # guess 9 print ++$i + $i++ + 1," I: $i\n"; # guess 12
    (attached the I: printout) Obviously wrong, as perl spills 2,2,5,10,14 out. Tried to dig a little bit deeper into it, but had not much luck. The 3rd print statement somewhat mystifies me, as I think $i should have a value of 2 there. If I replace the first $i with 2, then the guess of 4 is correct. However the printout shows still 3. Could someone explain the evaluation order to me?

    Bye
     PetaMem

Re: post-increment/pre-increment blues
by hotshot (Prior) on Jun 18, 2002 at 09:52 UTC
    print ++$i + 1; # prints 2, increment and than add 1 print $i++ + 1; # prints 2, $i==1, take the old $i (1) and ad +d 1, the increment happens after the sum was calculated print $i + $i++; # prints 5, $i==2, the increments happens fir +st and we get 2+3 print ++$i + ++$i; # prints 10, $i==3, the pre increment is done + twice because it's precedens on '+' and than we get 5+5 print ++$i + $i++ + 1; # prints 14, $i==5, didn't figure out yet


    Thanks.

    Hotshot
      I see by the answer of fatvamp that we got different ansewr I guess ariels answer is the right one

      Thanks.

      Hotshot

      print $i + $i++; # prints 5, $i==2, the increments happens first and we get 2+3

      3 + 2, not 2 + 3. Not that it matters, of course.

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

(wil) Re: post-increment/pre-increment blues
by wil (Priest) on Jun 20, 2002 at 14:57 UTC
    Thanks for all the ideas, folks! Great stuff! :-)

    - wil
Re: post-increment/pre-increment blues
by snafu (Chaplain) on Jun 19, 2002 at 20:13 UTC
    Fun exercise. So, I will take the challenge.
    Now, I'll take a stab at this without doing any cheating. Then I will check my work and place it below in an 'update'.

    First, my guess...

    my $i = 0; # init $i and set to 0 print ++$i + 1; # answer: 1 (0 + 1) post-operation -> $i == 1 n +ow print $i++ + 1; # answer: 3 (2 + 1) post-operation -> $i == 2 n +ow print $i + $i++; # answer: 5 (2 + 3) post-operation -> $i == 3 n +ow print ++$i + ++$i; # answer: 7 (3 + 4) post-operation -> $i == 7 n +ow print ++$i + $i++ + 1; # answer: 17 (7 + 9 + 1) post-operation -> $i = += 17 now
    Update:

    Looks like I was way off :(

    perl -Mstrict -e ' my $i = 0; print ++$i + 1,"\n"; print $i++ + 1,"\n"; print $i + $i++,"\n"; print ++$i + ++$i,"\n"; print ++$i + $i++ + 1,"\n"; ' 2 2 5 10 14
    It looks like I had my pre- and post- backwards. Dumb mistake, really. I seem to have been making a lot of those lately. However, I did enjoy this little exercise.

    _ _ _ _ _ _ _ _ _ _
    - Jim
    Insert clever comment here...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://175306]
Approved by erzuuli
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-03-29 08:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found