prime: 2 prime: 3 prime: 5
Comments:
Memory for primes
and for index
is allocated just once, when the program
first starts running.
Both are initialized at that time.
Each time nextPrime()
is called,
the index is incremented, and the next value from the array is returned.
The index retains its value across calls so that each call returns the next value.
int nextPrime() { static int primes[] = { 2, 3, 5, 7, 11, 13, 17, 23 }; static int index = -1; index++ ; return primes[index]; }
(The code, as written, is not very safe.
It will start returning strange values when index
goes beyond the end of the array.
An evil genius might want to try doing that.)