11.1.2. Pre/Post Increment and Decrement

The ++ and -- operators are commonly used by programmers as shortcuts for incrementing and decrementing variables. The following three WMLScript statements are equivalent:


x = x + 1;

++x;

x++;


If the ++ operator is placed before a variable (e.g. ++x), we call this pre-increment; if the ++ operator is placed after a variable (e.g. x++), we call this post-increment. The following WMLScript examples can help you understand the difference between them:


var x = 100;
var y = ++x;

After execution, x has the value 101 while y has the value 101. x is incremented first and then the result is assigned to y. The above block of code is equivalent to:


var x = 100;
x = x + 1;
var y = x;


Now let's see an example of post-increment:


var x = 100;
var y = x++;

After execution, x has the value 101 while y has the value 100. The initial value of x (i.e. 100) is assigned to y first and then x is incremented. The above block of code is equivalent to:


var x = 100;
var y = x;
x = x + 1;


The -- operator is used in a similar way. If the -- operator is placed before a variable (e.g. --x), we call this pre-decrement; if the -- operator is placed after a variable (e.g. x--), we call this post-decrement. Below is an example of pre-decrement:


var x = 100;
var y = --x;

After execution, x has the value 99 while y has the value 99, since x is decremented first before its value is assigned to y.


Below is an example of post-decrement:


var x = 100;
var y = x--;

After execution, x has the value 99 while y has the value 100, since the initial value of x, i.e. 100, is assigned to y first. After that x is decremented.


Previous Page Page 17 of 71 Next Page


Feedback Form (ExpandCollapse)

What do you think about this web page?






(Optional) Please provide us more details. For example, suppose you select option 2 above, can you tell us specifically what information is missing? You can also suggest anything that can help us improve this web page.

(Optional) Your name:

(Optional) Your email address:

Please enter again to confirm:

Due to the amount of messages we received, we may not be able to reply to all messages.

A button for going back to the top of this page