Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Why Why

Name: why 2010-10-29 14:11

int i=5;
i = ++i;
print(i);//prints 6

int i=5;
i = i++;
print(i);//prints 6

int i = 5;
i = i++ + ++i;
print(i);//prints 11?...........NO ITS 12. WHY

Name: Anonymous 2010-10-29 20:43

The behaviour of i = i++ + ++i; is undefined? Really? Wow, what a huge piece of shit of a language they have there. This expression should expand to:


(+ (let ((k i))
        (set! i (+ i 1)) k)
   (begin (set! i (+ i 1))
          i))


which will return 12. With Racket it's easy to understand why: you evaluate subexpressions from left to right. The first argument to + does return the original i (5), but it modifies i before the second argument is evaluated, which ends up returning the original i incremented twice.

So, what can we learn from this? Side effects are evil. Use functional programming.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List