Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  41] [ 6]  / answers: 1 / hits: 31225  / 11 Years ago, fri, june 21, 2013, 12:00:00

Could somebody explain why the following functions give different results. The first does not seem to work, but the second does. I'm puzzled because I thought +=1 and ++ did the same thing.



(I'm not intending to actually use this code, it's just to demonstrate the difference).



/*function 1*/
function incrementIfZero1(base,element) {

if (element == 0) {
return base++;
}
else
{
return base;
}
};


/*function 2*/
function incrementIfZero2(base,element) {

if (element == 0) {
return base+=1;
}
else
{
return base;
}
};

incrementIfZero1(1,0) /* -> 1*/
incrementIfZero2(1,0) /* -> 2*/


Any help is very much appreciated.



Thanks,



Robin



[Edit:]



Thank you for your replies, it makes sense now. I had also tried the following statement, which resulted in the same thing as function 1:



return (base++)


I'm now surprised that this doesn't give the same result as function 2 - I would have expected the brackets to 'force' it to be evaluated before returning. Any idea why this is not the case?


More From » increment

 Answers
57

when you return base++ it returns the value of base just before it gets incremented. You want to do ++base to make sure the increment happens first then it gets returned



otherwise ++ is the same as +=1



[edit] in response to your edit, i tried wrapping random statements in parentheses and most mathematical operators respond as expected, this incrementation seems to be exempt, likely because the syntax of pre-incrementation vs post-incrementation is highly intentional and the statement itself returns a specific value regardless of whether or not you wrap it in parentheses


[#77489] Thursday, June 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
patienceannel questions
Fri, Mar 11, 22, 00:00, 2 Years ago
Tue, Oct 20, 20, 00:00, 4 Years ago
Wed, Jul 24, 19, 00:00, 5 Years ago
;