Solved

pre and post increment, decrement operaotrs

Posted on 2000-05-08
22
419 Views
Last Modified: 2008-02-01
i am confused about pre and post increment operaotrs..
eg.

##first#########
$int=  5;
print"int=$int\n";
$int = ++$int + $int++ + $int--;
print"int=$int\n";

#output is 20              

##second#########
$int=  5;
print"int=$int\n";
$int = ++$int + --$int + $int++ + $int--;
print"int=$int\n";

##gives out put as 21
##third############

how does perl actually impliments the operators?
0
Comment
Question by:sushrut
  • 12
  • 4
  • 2
  • +3
22 Comments
 
LVL 84

Expert Comment

by:ozo
Comment Utility
You're lucky you didn't try that in C, where the behavior would be completely indefined.
$int = ($a=++$int) + ($b=$int++) + ($c=$int--);
and
$int = ($a=++$int) + ($b=--$int) + ($c=$int++) + ($d=$int--)
might force the behavior you may have been expecting, but I wouldn't recommend that you confuse yourself or your readers with side effects that way.
You should probably try to use side effects only in ways that would have a defined sequence in a strictly conforming C program.
0
 
LVL 16

Expert Comment

by:maneshr
Comment Utility
Autoincrement and Autodecrement

The
++ operator (called the autoincrement operator) adds one to its operand, and returns the incremented value, like so:

$a += 1;   # with assignment operator
++$a;      # with prefix autoincrement
$d = 17;
$e = ++$d; # $e and $d are both 18 now

Here, the ++ operator is being used as a prefix operator; that is, the operator appears to the left of its operand. The
autoincrement may also be used in a suffix form (to the right of its operand). In this case, the result of the expression is the old
value of the variable before the variable is incremented. For example:

$c = 17;
$d = $c++; # $d is 17, but $c is now 18

Because the value of the operand changes, the operand must be a scalar variable, not just an expression. You cannot say ++16
to get 17, nor can you say ++($a+$b) to somehow get one more than the sum of $a and $b.

The autodecrement operator (--) is similar to the autoincrement operator, but subtracts one rather than adding one. Like the
autoincrement operator, the autodecrement operator has a prefix and suffix form. For example:

$x = 12;
--$x;      # $x is now 11
$y = $x--; # $y is 11, and $x is now 10

The autoincrement and autodecrement operators also work on floating-point values. So autoincrementing a variable with the
value 4.2 yields 5.2 as expected.

Autoincrement even works on strings.

The autoincrement operator has a little extra built-in magic to it. If you increment a variable that is numeric, or that has ever
been used in a numeric context, you get a normal increment. If, however, the variable has only been used in string contexts
since it was set, and has a value that is not null and matches the pattern /^[a-zA-Z]*[0-9]*$/, the increment is done as a
string, preserving each character within its range, with carry:

print ++($foo = '99');      # prints '100'
print ++($foo = 'a0');      # prints 'a1'
print ++($foo = 'Az');      # prints 'Ba'
print ++($foo = 'zz');      # prints 'aaa'

The autodecrement operator, however, is not magical.
=========================================
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
Adjusted points from 50 to 100
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
for maneshr:::
well your explanation doesnot answer my question.
i know the diffrence between pre and post operators. i have used them lot of times. but i was still confused with their beheviour if they are used with each other and with itself.
eg.
$a = 5;
$a = $a++ + ++$a;

now $a is 12.
$a = 5;
$a = ++$a + $a++;
now $a is 13.
Can you please help me in understanding this?

alos ozo doesnot explain me what i want.
may be the points are too less. i will increase the points.


0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
for maneshr:::
well your explanation doesnot answer my question.
i know the diffrence between pre and post operators. i have used them lot of times. but i was still confused with their beheviour if they are used with each other and with itself.
eg.
$a = 5;
$a = $a++ + ++$a;

now $a is 12.
$a = 5;
$a = ++$a + $a++;
now $a is 13.
Can you please help me in understanding this?

alos ozo doesnot explain me what i want.
may be the points are too less. i will increase the points.


0
 
LVL 16

Expert Comment

by:maneshr
Comment Utility
lets take the first eg.

$a = 5;
$a = $a++ + ++$a;

the expression is evaluated from left to right. so we have 5 to start with when we encounter $a++. But since its a post increment operator and also since the entire expression has not been evaluated the value in variable a is not determined.

next we have the + sign followed by the pre increment operator which increments the value of a by 1 making it six.

but now that the entire expression has been evaluated, the value in a has become 6 making the return value as 12.

*********************************************

In the 2nd example

$a = 5;
$a = ++$a + $a++;

we start with 5. the preincrement op. makes it 6. next we have $a++ following the + sign. in this case note that we have reached the end of the expression. therefore this time the value of a is incremented by 1 making it 7. the final result is therefore 13.

The key to this is the foll....

The ++ and -- operators work as in C. That is, if placed before a variable, they increment or decrement the variable before
returning the value, and if placed after, they increment or decrement the variable AFTER returning the value.

Hope that helps.
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
#I don't recommend depending on this, but consider:
$a = 5;
@a = (++$a,$a++);
print "@a\n";
$a = $a[0] + $a[1];
0
 

Expert Comment

by:Saba050900
Comment Utility
Hi,

It is nice to try these examples. But when you write real time programming you need to be careful. It is fun to learn the language this way.

Anyhow my answers are:

1. The pre and post increment operators affect the inital $int variable.
2. The decrement does not affect the $int variable. It uses only in the expression evaluation.

More specific on example first:
 
$int=5
Expression $temp = ++$int + $int++ gives result of $temp as 13 and $int is now set to 7.

Next expressiong $temp=++$int + $int++ + $int--;  gives result of $temp as 20 ( 13+7) and now $int is set to 6.

Similarly try the second example. Do not ask me why the perl works this way. May be it is written this way to handle these operators.

Have fun.

0
 

Expert Comment

by:Saba050900
Comment Utility
Thanks
0
 
LVL 16

Expert Comment

by:maneshr
Comment Utility
sushrut,

has your question been answered?

let us know.

0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
i still want to know some thing more.
when you will answer this question, i will certainly give the points.


$a = 5;

$a = ++$a + $a++ + $a++;
print $a;


######################
$a = 5;

$a = ++$a + $a++ + $a--;
print $a;
#######################
both give output 20

##################
##################
##################

$a = 5;

$a = ++$a + $a-- + $a--;
print $a;
#########################
$a = 5;

$a = ++$a + $a-- + $a++;
print $a;
########################
both give output 16



How should i predict the beheviour?
i am not asking you to explain why but i need to know how to predict this.

is it that
once it finds pre++ it seems to take even pre -- as pre++ ( confused?? even i am)

whoever answers this i am gonna reward the points.

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 1

Author Comment

by:sushrut
Comment Utility
Adjusted points from 100 to 200
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
may be i am expecting tooo much for 100 points. so i will increase the points.
sorry for troubling....
0
 

Expert Comment

by:ihunter
Comment Utility
I can answer why each example gives the same answer, but I think that the answers should be different than they are:

>$a = 5;
>$a = ++$a + $a++ + $a++;
>print $a;
>######################
>$a = 5;
>$a = ++$a + $a++ + $a--;
>print $a;
>#######################
>both give output 20

Sure they're the same:
++$a + $a++ + $a++ is the same as
++$a + $a++ + $a--

because the at the very last part of the expression, you are POST-increment or POST-decrementing.  In other words, the value of $a++ is the same as the value of $a--, it's just that in one case $a ends up = 8, and in the other example, $a ends up = 6.  The value returned IN THE EXPRESSION should be 7 in any case.  The way I figure it,

$a = 5;
$a = ++$a + $a++ + $a++; # turns into
$a =  6   +  6   +  7    # and $a = 8

which should come out 19, but indeed it's 20.  ARGH!!!  WHY?!?!?


>$a = 5;
>$a = ++$a + $a-- + $a--;
>print $a;
>#########################
>$a = 5;
>$a = ++$a + $a-- + $a++;
>print $a;
>########################
>both give output 16

Here again,
++$a + $a-- + $a-- is the same thing as
++$a + $a-- + $a++
because you're using postfix increment/decrement as the last part of the expression.

I think it should turn out to be
$a=5;
$a=++$a + $a-- + $a--
    6   +   6  +  5
which should be 17 in my book, but it comes out 16, sure enough.  This is one for Larry Wall -- I suggest you contact him directly.


0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
maneshr:
I need ur suggestion. should i keep the topic open?
if i shouldnot, answer me and i will give you the point. (points are not important but the knowlege is important). But pls let me know whenever you get to know how to predict the beheviour.

###################################
However saba you were also good. I wish i could split the points.



0
 
LVL 16

Accepted Solution

by:
maneshr earned 200 total points
Comment Utility
sushrut ,

Frankly, after seeing your latest example, i am a bit stumped myself. i have a possible explanation of why you get 20 in the 1st 2 eg.s.

But if i apply the same logic to the second 2 eg.s, i dont get the expect answer!!

Sorry that i could not be of more help here. :-)

Rgds
0
 
LVL 3

Expert Comment

by:tgoetze
Comment Utility
Here's some more fuel for the fire.

Basically, it looks like ++$a is not returning what is advertised in the perl docs. It appears to be returning BEFORE the increment takes place in this case.

Code attached, need to read it and run it.

------ CUT HERE --------

$a = 5;
$c = ++$a + $a-- + $a++;
print "1: $c ", $a, "\n\n";
########################
$a = 5;
$a = (++$a + $a--) + $a++;
print "2: ", $a, "\n\n";

#######################
# Case 2 shows that + has left associativity, as most people expect
#######################
$a = 5;
$a = ++$a + ($a-- + $a++);
print "2A: ", $a, "\n\n";
#######################
# Case 2A shows that associativity matters, since ++ and -- are non-Associative
#######################

$a = 5;
$c = ((++$a) + ($bb = $a--)) + ($bbb = $a++);
print "3: $c ", $a, "  ",$b + 0," $bb $bbb \n\n";

#######################
# Case 3 shows what most people think is going on
#######################

$a = 5;
$c = (($b = ++$a) + ($bb = $a--)) + ($bbb = $a++);
print "4: $c ", $a, "  $b $bb $bbb \n\n";
#######################
# Case 4 shows that the first piece ($b = ++$a) returns 6 like people
#  expect since ++$a is supposed to return after incrementing. But notice
#  that now the result is 17 (what most people expect). Only possible reason
#  I can think of, is a Perl bug (implementation error on precedence).
#######################


$a = 5;
$c = (&prePlus + ($bb = $a--)) + ($bbb = $a++);
print "5: $c ", $a, "  $b $bb $bbb \n\n";
#######################
# Case 5 shows the same as case 4, but really isolating the ++$a call.
#######################

$a = 5;
$c = (&prePlus + &postSub) + &postSub;
print "6: $c ", $a, "  $b $bb $bbb \n\n";
#######################
# Case 6 is just like 5 with more isolation
#######################

$a = 5;
$c = (($b = &prePlus) + ($bb = &postSub)) + ($bbb = &postSub);
print "7: $c ", $a, "  $b $bb $bbb \n\n";
#######################
# Case 7 is nothing surprising, by now
#######################

sub prePlus {
    print "In prePlus and a is: $a\n";
    return ++$a;
}
sub postPlus {
    print "In postPlus and a is: $a\n";
    return $a++;
}
sub postSub {
    print "In postSub and a is: $a\n";
    return $a--;
}
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
manesher
seems nobody is commenting now.
better if i give the points to you.
but pls let me know the answer if whenever you get to know
my id is

sardeshmukh@email.com
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
manesher
seems nobody is commenting now.
better if i give the points to you.
but pls let me know the answer whenever you get to know
my id is

sardeshmukh@email.com
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
I think manesher gave the best answer.
0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
I think manesher gave the best answer. i am giving him points

0
 
LVL 1

Author Comment

by:sushrut
Comment Utility
Comment accepted as answer
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now