Saving the updated value of the variable, for the next call of the function?

My code below is trying to output the next power of 2 when the program is run, so ./powers would return 4, then if I run again, ./powers would return 8.
However it returns 4 every time, how do I get the variable num to save its last value?

#include <stdio.h>

int powers(void) {
    int num, power;
    num = 2;
    power = 2;
    num = num * power;
    printf("%d\n", num);
    return 0;
}

int main(void) {
    powers();
    return 0;
}

>Solution :

You make it persistent.
The easiest way (shortest route for a newbie) is to save it to a file and read it back from there at the start of the program, in case the file exists.
At least that is the answer to the question involving "when the program is run".
The answer for the question involving "next call of the function" is different. For that, i.e. when the program does not terminate in between and you call the function multiple times, e.g. in a loop, you can use a static variable, with the keyword static.

A simple example of a static variable, similar to your code is:

#include <stdio.h>

int powers(void) {
    int power;
    static int num = 2;
    power = 2;
    num = num * power;
    printf("%d\n", num);
    return 0;
}

int main(void) {
    powers();
    powers();
    return 0;
}

Which gets you an output of:

4
8

Leave a Reply