Saturday, May 08, 2010

Fun with Pre/Post Operators

Think you know how pre and post operators work? Test yourself by working out what the following programs print. Answers at the end of the post:

1.

void function(int val){
  if(val > 0){
    function(val-1);
  }
  print(val);
}

function(5);
2.
void function(int val){
  if(val > 0){
    function(--val);
  }
  print(val);
}

function(5);
3.
void function(int val){
  if(val > 0){
    function(val--);
  }
  print(val);
}

function(5);
4.
int a = 1;
b = a++ + ++a;
print(b);
Answers:
The first program is simple enough and prints out the numbers 5, 4, 3, 2, 1, 0.

The second program prints out the numbers 4, 3, 2, 1, 0, 0. --val decrements the value of the variable before assigning it. For example, if a=5, and b=--a, then b=4 and a=4.

The third program throws a StackOverflowError. val-- assigns the value of the variable first, before decrementing it. For example, if a=5, and b=a--, then b=5 and a=4.

The fourth program prints 4, because b = 1 + 3.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.