Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading