prefix, postfix and operator expectations

fronobulax

Developer
Staff member
Code:
int preinc(int num) {
   return ++num;
}
int postinc(int num) {
   return num++;
}
int postincp(int num) {
   return (num++);
}
int addinc(int num) {
   return num + 1;
}
int test = 0;
print("preinc "+preinc(test));
print("postinc "+postinc(test));
print("postincp "+postincp(test));
print("addinc "+addinc(test));

yields

> call scripts\Plus.ash

preinc 1
postinc 0
postincp 0
addinc 1

I would have expected ones for all cases.

The Operators page implies the prefix and postfix should both be performed before assignments and returning a value from a function seems to me similar in precedence.

Is this an ash bug or am I just projecting too much experience with other languages on ash?

Thanks.
 

xKiv

Active member
Your expectations are wrong in the other languages too.
The "test++" itself is performed before assignment, but its value is what test was before the incrementing.
 

adeyke

Member
I'm confused as to why you expected the result you expected. The difference between ++num and num++ is present in many languages. Both increment num, but the former evaluates to the value num has after incrementing while the latter evaluates to the value num has before incrementing. ASH also treats them this way.
 

fronobulax

Developer
Staff member
Thank you. Operator confusion, and there is a reason I tend to not use prefix and postfix operators in any language. I really, really want to forget that j = ++i and j = i++ change both variables unless I am iterating over something where I don't seem to confuse myself.

Move along, nothing else to see here.
 

Veracity

Developer
Staff member
I would have expected ones for all cases.
Your expectations are flawed.

The Operators page implies the prefix and postfix should both be performed before assignments and returning a value from a function seems to me similar in precedence.
You are incrementing the parameter of the function.
You are returning a value which is either the (prefix incremented) parameter - i.e., 1 - or the parameter - i.e. 0.
In either case, the parameter of the function is incremented.
Of course, when you exit the function, you leave the scope of the function, and that value is no longer accessible.

I see no bug.

Is this an ash bug or am I just projecting too much experience with other languages on ash?
I can't think of another language that behaves differently than what you demonstrated.
 
Top