Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does someArray[--n] mean?

Tags:

java

arrays

I tried googling this but Google doesn't handle "--n" well. I saw this in my professor's code:

f[--n];
f[n++];

where f is an array of double values.

My guess is that it returns the value of f[n] before reducing (or adding) to n.

like image 219
Firkamon Avatar asked Mar 17 '23 20:03

Firkamon


2 Answers

f[--n]; means :

n = n -1;
f[n];

f[n++]; means :

f[n];
n = n + 1;
like image 174
ToYonos Avatar answered Mar 24 '23 07:03

ToYonos


It's actually a type of operator called a pre-decrement, and it's part of a family of 4 operators (see table of java operators)

For an integer-type variable called n:

  1. post-increment n++ is the equivalent of n = n + 1, the 'post' part means that if you see it in a line of code (ex. foo(n++);) then the line of code will be called Before n is incremented.

  2. pre-increment ++n is also the same as n = n + 1 but it occurs Before the line of code it belongs in has been run.

  3. post-decrement n-- is the equivalent of n = n - 1 and occurs After the current line of code has been run

  4. pre-decrement --n is the equivalent of n = n - 1 and occurs Before the current line of code has been run

Example of post vs pre decrement:

int n = 5;

System.out.println(n--); //This prints 5
System.out.println(n); //This prints 4

System.out.println(--n); //This prints 3
System.out.println(n); //this prints 3
like image 45
Alter Avatar answered Mar 24 '23 07:03

Alter