Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Question preincrement

by himik (Acolyte)
on Aug 03, 2012 at 13:37 UTC ( [id://985234]=perlquestion: print w/replies, xml ) Need Help??

himik has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks! I have question

my $a=1; print ++$a + $a++;

How much will this print?

shouldn't it be 4? And not 5?

I test this in PHP and there is 5

1. in the start $a is 1

2. first of all in the print is ++$a and $a become 2

3. second is $a+$a and become 4

4. third is print

5. fourth $a become 3

Thank you

I found the answer in perldoc

Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:

$i = $i ++; print ++ $i + $i ++;

Replies are listed 'Best First'.
Re: Question preincrement
by choroba (Cardinal) on Aug 03, 2012 at 13:43 UTC
    Have you read the documentation?
    Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:
    $i = $i ++; print ++ $i + $i ++;
    Does the last line look familiar?
Re: Question preincrement
by toolic (Bishop) on Aug 03, 2012 at 13:42 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2024-04-20 05:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found