4

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.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Firkamon
  • 807
  • 1
  • 9
  • 19

4 Answers4

7

f[--n]; means :

n = n -1;
f[n];

f[n++]; means :

f[n];
n = n + 1;
ToYonos
  • 16,469
  • 2
  • 54
  • 70
1

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
Alter
  • 3,332
  • 4
  • 31
  • 56
0

you can look it up under predecrement (--n) or postincrement (n++). It works like this:

  • f[--n]: first n is reduced by 1 then the value of f[n] (this is already the reduced n) is returned
  • f[n++]: first the value of f[n] is returned then n is increased by 1

Example:

f {1,3,5} n=1;

  • f[--n] returns 1
  • f[n++] returns 3
markus
  • 1,631
  • 2
  • 17
  • 31
0

The code

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

Is the same as

n--;
f[n];
f[n];
n++;
Bohemian
  • 412,405
  • 93
  • 575
  • 722