View Single Post
Old 02-17-2013, 12:44 AM   #17
Kite
Human being with feelings
 
Join Date: Apr 2010
Location: Portland OR
Posts: 143
Default

For lack of an "Avoiding common Jesusonic mistakes" sticky thread, I'm posting here.

Wrong:
Code:
x = -5;
while (x < 5 ? (
  x += 1;
));
gfx_drawnumber (x, 0);     // Jesusonic returns "0"
Right:
Code:
x = -5;
while (x < 5 ? (
  x += 1;
  1;
));
gfx_drawnumber (x, 0);     // Jesusonic returns "5"
When Jesusonic increments x up to 0, that statement returns 0, which means false, and false statements at the end of while loops break the loop, so the while loop ends early.
Adding the "1;" statement ensures the last line of the while loop is true. Now the loop won't break until the if-condition is false.
Another way to write the while loop is to not use an if-statement and instead put the while-condition all by itself on the last line. If you do this, DON'T put in a "1;" or you'll get an infinite loop:

Right:
Code:
x = -5;
while (
  x += 1;
  x < 5;
);
gfx_drawnumber (x, 0);     // Jesusonic returns "5"
Wrong:
Code:
x = -5;
while (
  x += 1;
  x < 5;
  1;
);
gfx_drawnumber (x, 0);     // Jesusonic loops forever and returns nothing
Kite is offline   Reply With Quote